mirror of
https://github.com/rust-lang-nursery/rust-cookbook
synced 2024-11-22 03:23:05 +00:00
(de)-serialize a matrix (#589)
* (de)-serialize a matrix * enable serde-serialize for nalgebra * fix typo * add references
This commit is contained in:
parent
67329add00
commit
019c0a0d2c
3 changed files with 35 additions and 1 deletions
|
@ -30,7 +30,7 @@ log = "0.4"
|
|||
log4rs = "0.8"
|
||||
memmap = "0.7"
|
||||
mime = "0.3"
|
||||
nalgebra = "0.16.12"
|
||||
nalgebra = { version = "0.16.12", features = ["serde-serialize"] }
|
||||
ndarray = { version = "0.13", features = ["approx"] }
|
||||
num = "0.2"
|
||||
num_cpus = "1.8"
|
||||
|
|
|
@ -6,5 +6,6 @@
|
|||
{{#include linear_algebra/vector-comparison.md}}
|
||||
{{#include linear_algebra/vector-norm.md}}
|
||||
{{#include linear_algebra/invert-matrix.md}}
|
||||
{{#include linear_algebra/deserialize-matrix.md}}
|
||||
|
||||
{{#include ../../links.md}}
|
||||
|
|
33
src/science/mathematics/linear_algebra/deserialize-matrix.md
Normal file
33
src/science/mathematics/linear_algebra/deserialize-matrix.md
Normal file
|
@ -0,0 +1,33 @@
|
|||
## (De)-Serialize a Matrix
|
||||
[![ndarray-badge]][ndarray] [![cat-science-badge]][cat-science]
|
||||
|
||||
Serialize and deserialize a matrix to and from JSON. Serialization is taken care of
|
||||
by [`serde_json::to_string`] and [`serde_json::from_str`] performs deserialization.
|
||||
|
||||
Note that serialization followed by deserialization gives back the original matrix.
|
||||
|
||||
```rust
|
||||
extern crate nalgebra;
|
||||
extern crate serde_json;
|
||||
|
||||
use nalgebra::DMatrix;
|
||||
|
||||
fn main() -> Result<(), std::io::Error> {
|
||||
let row_slice: Vec<i32> = (1..5001).collect();
|
||||
let matrix = DMatrix::from_row_slice(50, 100, &row_slice);
|
||||
|
||||
// serialize matrix
|
||||
let serialized_matrix = serde_json::to_string(&matrix)?;
|
||||
|
||||
// deserialize matrix
|
||||
let deserialized_matrix: DMatrix<i32> = serde_json::from_str(&serialized_matrix)?;
|
||||
|
||||
// verify that `deserialized_matrix` is equal to `matrix`
|
||||
assert!(deserialized_matrix == matrix);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
```
|
||||
|
||||
[`serde_json::to_string`]: https://docs.rs/serde_json/*/serde_json/fn.to_string.html
|
||||
[`serde_json::from_str`]: https://docs.rs/serde_json/*/serde_json/fn.from_str.html
|
Loading…
Reference in a new issue