What is the best way to work with matrices?

Hello, i'm working with matrixes and i have a question: what crate should i use ? Or maybe i don't need one ?

For example, i want to process a NXN matrix and make operations between cells. I saw different crates like ndarray, nalgebra, array2d, etc. What are the differences ? And why there isn't an standard crate ?

I saw in one answer in the forum that a guy create the matrix with:

type Matrix = [ [f32; N]; N];

let matrix = unsafe {
    let layout = std::alloc::Layout::new::<Matrix>();
    let ptr = std::alloc::alloc_zeroed(layout) as *mut Matrix;

And that works very well, but i don't understand why the matrix is created like this and either why accessing to this matrix is faster than access to ndarray matrix, for example.

I would appreciate that tell me your experiences and suggestions.

This forum is incredible. Thank you so much.

1 Like

nalgebra is the standard way to deal with matrices. You shouldn't have to use allocations to work with matricies, or even unsafe code.

And nalgebra is the standard for big matrixes too ?

That code snippet turned up in one of my threads. Clippy driving me to insanity, insisting on iterators You would have to read it all to get the whole story.

That is solving what is perhaps a specific problem. Namely producing what is effectively a transpose of a large matrix in a performant manner. That requires operations to be done in a cache friendly way.

Specifically I wanted the matrix to be stored in contiguous memory, not a Vec of Vecs. I wanted to be able to index that data as a 2d array, like "a[i][j] += b[j][i];" rather than synthesize it with "a[i * n + j]" or whatever.

Significantly I wanted the performance to match what one can achieve easily in C for this.

That complicated matrix creation you quote there came about because it turns out that if you initialize a large 2D array of the kind I describe the simple way then the program crashes out with a stack overflow.

Yes, nalgebra has a number of different ways to handle matricies, large and small.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.