这是一个用C语言编写的矩阵运算头文件,话不多说,上代码
matrix.h
/**
* File name: matrix.h
* Author: Tiancai Xu
* Version: 1.0
* Data: 2021-10-29
* Copyright: 2021.10, Tiancai Xu
* This file defines the matrix and its basic operations
* This file is for study or reference only
*/
#ifndef _STDARG_H
#include <stdarg.h>
#endif // _STDARG_H
#ifndef _STDIO_H
#include <stdio.h>
#endif // _STDIO_H
#ifndef _STDLIB_H
#include <stdlib.h>
#endif // _STDLIB_H
#ifndef _TIME_H
#include <time.h>
#endif // _TIME_H
#ifndef _MATRIX_H
#define _MATRIX_H
#define size_m unsigned int
/**< Matrix variable */
typedef struct
{
double** M; /**< Data of Matrix */
size_m row; /**< The number of row */
size_m col; /**< The number of column */
} Matrix;
/**< Tips: This format is recommended for declarations: Matrix M = {NULL, 0, 0}; */
Matrix from(double* arr, size_m row, size_m col);
Matrix zeros(size_m row, size_m col);
Matrix ones(size_m row, size_m col);
Matrix diag(int order, ...);
Matrix diag_M(Matrix A);
Matrix iden(int order);
Matrix randM(size_m row, size_m col);
Matrix add(Matrix A, Matrix B);
Matrix sub(Matrix A, Matrix B);
Matrix mult_MM(Matrix A, Matrix B);
Matrix mult_kM(double k, Matrix B);
Matrix T(Matrix A);
Matrix inv(Matrix A);
Matrix cof(Matrix A, int r, int c);
double mode(Matrix A);
void scanM(Matrix* A);
void printM(Matrix A);
void clearM(Matrix* A);
#endif // _MATRIX_H
matrix.c
/**
* File name: matrix.c
* Author: Tiancai Xu
* Version: 1.0
* Data: 2021-10-29
* Copyright: 2021.10, Tiancai Xu
* This file includes the implementation of the functions declarated in matrix.h
* This file is for study or reference only
*/
#include "matrix.h"
/** \brief Create a block of 2-D array memory
*
* \param row The number of row
* \param col The number of column
* \return M 2-D array pointer
*
*/
static double** getM(size_m row, size_m col)
{
int i;
double** M;
M = (double**)malloc(sizeof(double*) * row);
for (i = 0; i < row; i++)
*(M + i) = (double*)malloc(sizeof(double) * col);
return M;
}
/** \brief Transform a 2-D array to Matrix
*
* \param arr The first adress of the a-D array
* \param row The number of row
* \param col The number of column
* \return M Matrix
*
* For a 2-D array arr[r][c], use from((double*)arr,r,c) to avoid the gcc compiler warning
*/
Matrix from(double* arr, size_m row, size_m col)
{
int i, j;
Matrix M;
M.row = row;
M.col = col;
M.M = getM(row, col);
for (i = 0; i < row; i++)
for (j = 0; j < col; j++)