Skip to content

Commit 019c0a0

Browse files
(de)-serialize a matrix (#589)
* (de)-serialize a matrix * enable serde-serialize for nalgebra * fix typo * add references
1 parent 67329ad commit 019c0a0

File tree

3 files changed

+35
-1
lines changed

3 files changed

+35
-1
lines changed

Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ log = "0.4"
3030
log4rs = "0.8"
3131
memmap = "0.7"
3232
mime = "0.3"
33-
nalgebra = "0.16.12"
33+
nalgebra = { version = "0.16.12", features = ["serde-serialize"] }
3434
ndarray = { version = "0.13", features = ["approx"] }
3535
num = "0.2"
3636
num_cpus = "1.8"

src/science/mathematics/linear_algebra.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,5 +6,6 @@
66
{{#include linear_algebra/vector-comparison.md}}
77
{{#include linear_algebra/vector-norm.md}}
88
{{#include linear_algebra/invert-matrix.md}}
9+
{{#include linear_algebra/deserialize-matrix.md}}
910

1011
{{#include ../../links.md}}
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
## (De)-Serialize a Matrix
2+
[![ndarray-badge]][ndarray] [![cat-science-badge]][cat-science]
3+
4+
Serialize and deserialize a matrix to and from JSON. Serialization is taken care of
5+
by [`serde_json::to_string`] and [`serde_json::from_str`] performs deserialization.
6+
7+
Note that serialization followed by deserialization gives back the original matrix.
8+
9+
```rust
10+
extern crate nalgebra;
11+
extern crate serde_json;
12+
13+
use nalgebra::DMatrix;
14+
15+
fn main() -> Result<(), std::io::Error> {
16+
let row_slice: Vec<i32> = (1..5001).collect();
17+
let matrix = DMatrix::from_row_slice(50, 100, &row_slice);
18+
19+
// serialize matrix
20+
let serialized_matrix = serde_json::to_string(&matrix)?;
21+
22+
// deserialize matrix
23+
let deserialized_matrix: DMatrix<i32> = serde_json::from_str(&serialized_matrix)?;
24+
25+
// verify that `deserialized_matrix` is equal to `matrix`
26+
assert!(deserialized_matrix == matrix);
27+
28+
Ok(())
29+
}
30+
```
31+
32+
[`serde_json::to_string`]: https://docs.rs/serde_json/*/serde_json/fn.to_string.html
33+
[`serde_json::from_str`]: https://docs.rs/serde_json/*/serde_json/fn.from_str.html

0 commit comments

Comments
 (0)