百科.dev
全部条目在线工具AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
N

neat-matrix-library

> 数据库
开源

nml 是一款用纯 C 编写的"简单"矩阵/数值分析库。该库的范围是突出与 mat 相关的各种算法实现。

99 stars0 点赞6 次浏览
访问官网GitHub

工具介绍

nml 是一款用纯 C 编写的"简单"矩阵/数值分析库。该库的范围是突出与 mat 相关的各种算法实现。

…

nml is a simple matrix and linear algebra library written in standard C.

Code should be portable and there are no dependencies.

For a detailed explanation of the library code please check this blog post.

It currently supports:

  • Basic Matrix Operations (row swaps, colum swaps, multiplication, addition, etc.)
  • LU Decomposition;
  • Inverse(A);
  • Determinant(A)
  • Solving linear systems of equations;
  • Row Echelon Form;
  • Reduced Row Echelon Form (Gauss-Jordan);
  • QR decomposition

The library is still under development, but a few thousands test cases are already implemented, covering the most complex algorithms (REF, RREF, LUP, QR, DET, INV, BACKWARD SUBSTITION, FORWARD SUBSTITION, etc.)

Table of Contents

  • Compile / Run Examples
    • Building the library
    • Building the examples
    • Running the tests
    • Cleaning
  • How to use the library
    • Creating matrices
      • Creating a new Matrix
      • Creating a marray from an array (double[N])
      • Creating a Matrix from an external file
      • Creating a matrix from user input
      • Creating randomized matrices
    • Check if two matrices are equal
    • Accesing and modifying matrix elements
      • Select rows and columns
      • Set all elements to a value
      • Set the first diagonal to a value
      • Scalar multiply the matrix
      • Multiply rows
      • Add rows
    • Modifying the matrix structure
      • Remove rows and columns
      • Swap rows and columns
      • Concatenate matrices
    • Matrices operations
      • Add and subtract matrices
      • Multiply matrices (dot)
    • Transpose matrices
    • Calculate trace
    • Row Echelon
      • Calculate Row Echelon Form using Gaussian Elimination
      • Calculate Reduced Row Echelon Form using Gauss-Jordan
    • LU(P) Decomposition
    • Matrix inverse
    • Matrix determinant
    • Solve linear systems of equations

Compile / Run Examples

The build file for the library it's called nml.sh. It's actually a bash script (not a makefile!).

Building the library

bash
./nml.sh clean build

This will compile the library, create a dist folder where you will find *.a static library file and the header files.

gcc and ar should be available in $PATH.

If you want to use the clang compiler instead of gcc you need to manually edit the ./nml.sh file, changing the variable CC from gcc to clang. Nothing else should be changed.

bash
# COMPILING RELATED
CC=clang #.ex
./nml.sh clean examples && ./examples/playground.ex

Running the tests

To run the tests

bash
./nml.sh clean test
  1. This will create a test/lib folder where the libnml.a and the header files will be copied;
  2. Each test tests/*.c will be compiled with the latest version of libnml;
  3. For each test tests/*/c an executable (*.ex) will be created.

The test data was generated using sympy. In the tests/generators/ folder you can find the python3 (.py) scripts used to generate the data.

Cleaning

bash
./nml.sh clean

This will clean everything (*.o,*.ex,*.a) and will leave the library folder in a clean state.

How to use the library

A few examples can be found in the ./examples folder folder.

Creating matrices

All the methods are interacting with the nml_mat struct:

c
typedef struct nml_mat_s {
  unsigned int num_rows;
  unsigned int num_cols;
  double **data;
  int is_square;
} nml_mat;

To interact the elements of the matrix:

c
nml_mat *m = ...
m->data[i][j] = ...

Creating a new Matrix

The methods for a creating a new matrix are:

  • nml_mat *nml_mat_new(unsigned int num_rows, unsigned int num_cols)
    • Creates a num_rows * num_cols matrix of zeroes.
  • nml_mat *nml_mat_sqr(unsigned int size)
    • Creates a square size * size matrix of zeroes.
  • nml_mat *nml_mat_eye(unsigned int size)
    • Creates an identity size * size matrix.
  • nml_mat *nml_mat_cp(nml_mat *m)
    • Returns a new identitcal copy of matrix m.

Everytime we create a matrix, we dynamically allocate memory. To free the memory please use: nml_mat_free(nml_mat *m).

c
#include 
#include 

#include "lib/nml.h"

int main(int argc, char *argv[]) {

  nml_mat* m, *mx;

  printf("\nCreating an empty matrix with 2x3\n");
  m = nml_mat_new(2,3);
  nml_mat_print(m);
  nml_mat_free(m);

  printf("\nCreating a square matrix 5x5 \n");
  m = nml_mat_sqr(5);
  nml_mat_print(m);
  nml_mat_free(m);

  printf("\nCreating an ID 7x7 Matrix and copying it into another matrix:\n");
  m = nml_mat_eye(7);
  mx = nml_mat_cp(m);
  nml_mat_print(m);
  nml_mat_print(mx);
  nml_mat_free(m);
  nml_mat_free(mx);

  return 0;
}

To run the example:

bash
./nml.sh clean examples && examples/creating_a_matrix.ex

Creating a marray from an array (double[N])

An array can be used as the "data source" for the Matrix by using:

  • nml_mat *nml_mat_from(unsigned int num_rows, unsigned int num_cols, unsigned int n_vals, double *vals)
    • num_rows and num_cols represent the dimensions of the matrix;
    • n_vals how many values to read from the vals source. If n_vals is smaller than the product num_cols * num_rows, 0.0 will be used as the default value;
    • vals the array containing double values.
c
#include 
#include 

#include "lib/nml.h"

int main(int argc, char *argv[]) { 
    double array[6] = { 
        1.0, 0.2, 3.0, 4.0, 5.0, 3.1 
    };
    nml_mat* my;
    
    // 3 rows, 2 columns
    // read exactly 6 numbers from array[6]
    my = nml_mat_from(3, 2, 6, array);
    nml_mat_print(my);
    nml_mat_free(my);

    // 4 rows, 2 columns
    // read exactly 3 numbers from array[6]
    my = nml_mat_from(4, 2, 3, array);
    nml_mat_print(my);
    nml_mat_free(my);

    return 0;
}

To run the example:

bash
./nml.sh clean examples && examples/creating_a_matrix_from_an_array.ex

Creating a Matrix from an external file

The two methods that can be used to create a matrix from a file on disk are:

  • nml_mat *nml_mat_fromfile(const char *file)
    • Create a matrix from the file path. If the file cannot be opened a NULL matrix will be returned.
  • nml_mat *nml_mat_fromfilef(FILE *f)
    • Creates a matrix from am already opened stream f. Does not automatically close the stream (FILE).

In the file, the matrix has the following format:

4 5
0.0     1.0     2.0     5.0     3.0
3.0     8.0     9.0     1.0     4.0
2.0     3.0     7.0     1.0     1.0
0.0     0.0     4.0     3.0     8.0

On the first line 4 represents the number of rows and 5 represents the number of columns of the Matrix Then next lines contain the matrix elements: 4 * 5 = 20 numbers.

Example code:

c
#include 
#include 

#include "lib/nml.h"

int main(int argc, char *argv[]) {
    const char *f = "examples/data/matrix1.data";
    nml_mat *from_file = nml_mat_fromfile(f);
    nml_mat_print(from_file);
    nml_mat_free(from_file);

    // Or if the file is already opened

    FILE *m_file = fopen("examples/data/matrix2.data", "r");
    nml_mat *from_file2 = nml_mat_fromfilef(m_file);
    nml_mat_print(from_file2);
    nml_mat_free(from_file2);
    fclose(m_file);

    return 0;
}

To run the example:

bash
./nml.sh clean examples && ./examples/creating_a_matrix_from_file.ex

Creating a matrix from user input

The nml_mat *nml_mat_fromfilef(FILE *f) can be called, with f=stdin.

Code example:

c
#include 
#include 

#include "lib/nml.h"

int main(int argc, char *argv[]) {
    nml_mat *from_file2 = nml_mat_fromfilef(stdin);
    nml_mat_print(from_file2);
    nml_mat_free(from_file2);
    return 0;
}

To run the example:

bash
./nml.sh clean examples && examples/creating_a_matrix_from_user_input.ex

Creating randomized matrices

Creating a randomized matrix can be done with the following two methods:

  • nml_mat *nml_mat_rnd(unsigned int num_rows, unsigned int num_cols, double min, double max)
    • Creates a randomized matrix of size num_rows * num_cols;
    • The random values are between min and max;
  • nml_mat *nml_mat_sqr_rnd(unsigned int size, double min, double max)
    • Creates a randomized matrix of size size * size;
    • The random values are between min and max;
c
#include 
#include 
#include 

#include "lib/nml.h"

int main(int argc, char *argv[]) {
  srand(time(NULL)); // Should be called once per program
  nml_mat *m = nml_mat_rnd(5, 5, -10.0, 10.0);
  nml_mat_print(m);
  nml_mat_free(m);
  return 0;
}

To run the example:

bash
./nml.sh clean examples && examples/create_randomized_matrix.ex

Check if two matrices are equal

There are two "equality" methods for matrices:

  • int nml_mat_eqdim(nml_mat *m1, nml_mat *m2)

    • Tests if two matrices have the same dimension.
  • int nml_mat_eq(nml_mat *m1, nml_mat *m2, double tolerance)

    • Test if two matrices are equal:
      • They have the same dimensions
      • The elements are equal or close of being equal.
    • If you want the elements to be "exactly" eqaul, tolerance=0.0
c
#include 
#include 
#include 

#include "lib/nml.h"

int main(int argc, char *argv[]) {

    srand(time(NULL));
    nml_mat *m1 = nml_mat_rnd(2, 3, 1.0, 10.0);
    nml_mat *m2 = nml_mat_rnd(2, 3, 1.0, 10.0);

    if (nml_mat_eq(m1, m2, 0.001)) {
        printf("Wow, what were the oddss..\n");
    } else {
        printf("It's ok, nobody is that lucky!\n");
    }
    if (nml_mat_eqdim(m1, m2)) {
        printf("At least we know they both have the same number of rows and columns.\n");
    }

    nml_mat_free(m1);
    nml_mat_free(m2);
    return 0;
}

To run the example:

bash
./nml.sh clean examples && ./examples/matrix_equality.ex

Accesing and modifying matrix elements

Select rows and columns

Two methods can be used to select rows and columns from a source matrix (nml_mat*):

  • nml_mat *nml_mat_col_get(nml_mat *m, unsigned int col)
  • nml_mat *nml_mat_row_get(nml_mat *m, unsigned int row)

The following code extracts every column of a given random matrix into a temporary column matrix (nml_mat*):

c
#include 
#include 
#include 

#include "lib/nml.h"

int main(int argc, char *argv[]) {
  printf("\nExtract all matrix columns from a Matrix as matrice

Issues· 0 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

Cansi-ccgauss-eliminationgauss-jordan

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月18日
分类数据库
定价开源

> 相关工具

P
PostgreSQL
功能强大的开源关系型数据库
R
Redis
内存数据结构存储,常用作缓存与队列
M
MySQL
广泛使用的开源关系型数据库