定义矩阵类型
矩阵显示
矩阵的等于运算
创建0矩阵
创建1矩阵
创建单位矩阵
矩阵的转置
矩阵的加法
矩阵与系数相乘
矩阵与矩阵相乘
#include <stdio.h>
#define MAX_MATRIX_SIZE 10
// 1、定义矩阵类型
typedef struct Matrix
{
float array[MAX_MATRIX_SIZE][MAX_MATRIX_SIZE];
int row;
int col;
} matrix_t;
// 2、矩阵显示
void matrix_display(matrix_t *A)
{
int i, j;
for (i = 0; i < A->row; i )
{
printf("[ ");
for (j = 0; j < A->col; j )
{
printf("%.4f ", A->array[i][j]);
}
printf("]\n");
}
}
// 3、矩阵的等于运算
void matrix_equal(matrix_t *A_equal, matrix_t *A)
{
int i, j;
for (i = 0; i < A->row; i )
{
for (j = 0; j < A->col; j )
{
A_equal->array[i][j] = A->array[i][j];
}
}
A_equal->row = A->row;
A_equal->col = A->col;
}
// 4、创建零矩阵
void matrix_zeros(matrix_t *A, int row, int col)
{
int i, j;
for (i = 0; i < row; i )
{
for (j = 0; j < col; j )
{
A->array[i][j] = 0.0;
}
}
A->row = row;
A->col = col;
}
// 5、创建1矩阵
void matrix_ones(matrix_t *A, int row, int col)
{
int i, j;
for (i = 0; i < row; i )
{
for (j = 0; j < col; j )
{
A->array[i][j] = 1.0;
}
}
A->row = row;
A->col = col;
}
// 6、创建单位矩阵
void matrix_eye(matrix_t *A, int row, int col)
{
int i, j;
for (i = 0; i < row; i )
{
for (j = 0; j < col; j )
{
A->array[i][j] = ((i == j) ? 1.0 : 0.0);
}
}
A->row = row;
A->col = col;
}
// 7、矩阵的转置
void matrix_transpose(matrix_t *AT, matrix_t *A)
{
int i, j;
for (i = 0; i < A->row; i )
{
for (j = 0; j < A->col; j )
{
AT->array[j][i] = A->array[i][j];
}
}
AT->row = A->col;
AT->col = A->row;
}
// 8、矩阵的加法
void matrix_add(matrix_t *sum, matrix_t *A, matrix_t *B)
{
int i, j;
for (i = 0; i < A->row; i )
{
for (j = 0; j < A->col; j )
{
sum->array[i][j] = A->array[i][j] B->array[i][j];
}
}
sum->row = A->row;
sum->col = A->col;
}
// 9、矩阵与系数相乘
void matrix_multiply_by_factor(matrix_t *Ak, matrix_t *A, float k)
{
int i, j;
for (i = 0; i < A->row; i )
{
for (j = 0; j < A->col; j )
{
Ak->array[i][j] = A->array[i][j] * k;
}
}
Ak->row = A->row;
Ak->col = A->col;
}
// 10、矩阵与矩阵相乘
void matrix_multiply_by_matrix(matrix_t *C, matrix_t *A, matrix_t *B)
{
int i, j, k;
float sum;
C->row = A->row;
C->col = B->col;
for (i = 0; i < C->row; i )
{
for (j = 0; j < C->col; j )
{
sum = 0.0;
for (k = 0; k < A->col; k )
{
sum = A->array[i][k] * B->array[k][j];
}
C->array[i][j] = sum;
}
}
}
Copyright © 2024 妖气游戏网 www.17u1u.com All Rights Reserved