forked from M-Labs/nalgebra
4a6022d9bf
There are two major additions in this commit. The first is a new storage trait, `ReshapableStorage`, that can be implemented for storage types that can be reshaped in-place. I have implemented this for both the `ArrayStorage` and `VecStorage` types, as they are the most common and they are just interpretations of a flat list. The second is a `Matrix::reshape_generic` method that allows matrices to be in-place reshaped provided that the underlying storage can handle it. In practice, this means that the standard matrix types (`MatrixMN` and `DMatrix`) can be resized to any size that has the same element count. Resizing between array and vector storage is not implemented due to `Storage` only being implemented for `VecStorage` variants where at least one dimension is `Dynamic`. Additionally, only the generic reshape function is added as it can be a basis for other reshaping functions (see the resizing functions) and I am not particularly in the mood to implement a variety of reshaping methods.
34 lines
1.1 KiB
Rust
34 lines
1.1 KiB
Rust
extern crate nalgebra as na;
|
|
|
|
use na::{DMatrix, Dynamic, Matrix2x3, Matrix3x2, U2, U3};
|
|
|
|
fn main() {
|
|
// Matrices can be reshaped in-place without moving or copying values.
|
|
let m1 = Matrix2x3::new(1.1, 1.2, 1.3, 2.1, 2.2, 2.3);
|
|
let m2 = Matrix3x2::new(1.1, 2.2, 2.1, 1.3, 1.2, 2.3);
|
|
|
|
let m3 = m1.reshape_generic(U3, U2);
|
|
assert_eq!(m3, m2);
|
|
|
|
// Note that, for statically sized matrices, invalid reshapes will not compile:
|
|
//let m4 = m3.reshape_generic(U3, U3);
|
|
|
|
// If dynamically sized matrices are used, the reshaping is checked at run-time.
|
|
let dm1 = DMatrix::from_vec(
|
|
4,
|
|
3,
|
|
vec![1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0],
|
|
);
|
|
let dm2 = DMatrix::from_vec(
|
|
6,
|
|
2,
|
|
vec![1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0],
|
|
);
|
|
|
|
let dm3 = dm1.reshape_generic(Dynamic::new(6), Dynamic::new(2));
|
|
assert_eq!(dm3, dm2);
|
|
|
|
// Invalid reshapings of dynamic matrices will panic at run-time.
|
|
//let dm4 = dm3.reshape_generic(Dynamic::new(6), Dynamic::new(6));
|
|
}
|