From 019c0a0d2cb2ffde562da4c466d090f5854c7995 Mon Sep 17 00:00:00 2001 From: Stefan Mesken Date: Sat, 13 Jun 2020 23:18:33 +0200 Subject: [PATCH] (de)-serialize a matrix (#589) * (de)-serialize a matrix * enable serde-serialize for nalgebra * fix typo * add references --- Cargo.toml | 2 +- src/science/mathematics/linear_algebra.md | 1 + .../linear_algebra/deserialize-matrix.md | 33 +++++++++++++++++++ 3 files changed, 35 insertions(+), 1 deletion(-) create mode 100644 src/science/mathematics/linear_algebra/deserialize-matrix.md diff --git a/Cargo.toml b/Cargo.toml index 4a76bc0..9e01325 100755 --- a/Cargo.toml +++ b/Cargo.toml @@ -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" diff --git a/src/science/mathematics/linear_algebra.md b/src/science/mathematics/linear_algebra.md index bc339c0..9ce7ae4 100644 --- a/src/science/mathematics/linear_algebra.md +++ b/src/science/mathematics/linear_algebra.md @@ -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}} diff --git a/src/science/mathematics/linear_algebra/deserialize-matrix.md b/src/science/mathematics/linear_algebra/deserialize-matrix.md new file mode 100644 index 0000000..49ddb7a --- /dev/null +++ b/src/science/mathematics/linear_algebra/deserialize-matrix.md @@ -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 = (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 = 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