C语言矩阵运算

本文档介绍了用C语言编写的矩阵操作头文件matrix.h,包括矩阵创建(零矩阵、单位矩阵、对角矩阵)、基本运算(加减乘、转置、逆矩阵)、辅助函数(系数矩阵、行列式计算)以及矩阵输入输出。矩阵操作涉及从一维数组构造、内存管理到高级数学运算。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这是一个用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++)
        
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值