Search code examples
rustnalgebra

Rust: nalgebra transpose


I've started to practice rust. I've run the program and got:

VecStorage { data: [1.0, 88.0, 87.0, 1.0, 70.0, 77.0, 1.0, 80.0, 79.0, 1.0, 82.0, 85.0, 1.0, 90.0, 97.0, 1.0, 100.0, 98.0], nrows: Dynamic { value: 6 }, ncols: Dynamic { value: 3 } }
VecStorage { data: [1.0, 1.0, 1.0, 88.0, 80.0, 90.0, 87.0, 79.0, 97.0, 1.0, 1.0, 1.0, 70.0, 82.0, 100.0, 77.0, 85.0, 98.0], nrows: Dynamic { value: 3 }, ncols: Dynamic { value: 6 } }

main.rs:

let matrix = vec![1.0,88.0,87.0,1.0,70.0,77.0,1.0,80.0,79.0,1.0,82.0,85.0,1.0,90.0,97.0,1.0,100.0,98.0];
    let matrix =  DMatrix::from_vec(6,3,matrix);
    println!("{:?}",matrix);
    println!("{:?}",matrix.transpose());

However transpose matrix is different(from the correct transpose), any ideas why?


Solution

  • According to the documentation, the matrix is filled from vector in column-major order. I suspect from the provided data that you're expecting a row-major one (with a first column of the original matrix holding only 1s).

    We can see this if we use Display formatting instead of Debug - the output in this case is the following:

      ┌             ┐
      │   1   1   1 │
      │  88  80  90 │
      │  87  79  97 │
      │   1   1   1 │
      │  70  82 100 │
      │  77  85  98 │
      └             ┘
    
      ┌                         ┐
      │   1  88  87   1  70  77 │
      │   1  80  79   1  82  85 │
      │   1  90  97   1 100  98 │
      └                         ┘
    

    Playground