rustHow to add matrices in Rust?
Adding matrices in Rust is a simple task. The zip() method can be used to iterate over two matrices at the same time and add the corresponding elements. The following example code adds two matrices a and b and stores the result in c:
let a = vec![vec![1, 2], vec![3, 4]];
let b = vec![vec![5, 6], vec![7, 8]];
let mut c = vec![vec![0, 0], vec![0, 0]];
for (i, row) in a.iter().enumerate() {
for (j, a_ij) in row.iter().enumerate() {
c[i][j] = a_ij + b[i][j];
}
}
The output of the example code is:
[[6, 8], [10, 12]]
The code consists of the following parts:
let a = vec![vec![1, 2], vec![3, 4]];creates a 2x2 matrixawith elements1,2,3and4.let b = vec![vec![5, 6], vec![7, 8]];creates a 2x2 matrixbwith elements5,6,7and8.let mut c = vec![vec![0, 0], vec![0, 0]];creates a 2x2 matrixcwith elements0,0,0and0.for (i, row) in a.iter().enumerate() {iterates over the rows of matrixa.for (j, a_ij) in row.iter().enumerate() {iterates over the elements of the current row of matrixa.c[i][j] = a_ij + b[i][j];adds the corresponding elements of matricesaandband stores the result in matrixc.
Helpful links
Related
More of Rust
- How to match whitespace with a regex in Rust?
- How to use captures_iter with regex in Rust?
- How to use regex to match a double quote in Rust?
- How do I print a variable in Rust?
- How to use regex lookbehind in Rust?
- How to create a Rust regex from a string?
- How to use regex to match a group in Rust?
- How to perform matrix operations in Rust?
- How to compare two HashSets in Rust?
- How to use Unicode in a regex in Rust?
See more codes...