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 a URL with a regex in Rust?
- Regex example to match multiline string in Rust?
- How to use binary regex in Rust?
- How to match the end of a line in a Rust regex?
- How to replace a capture group using Rust regex?
- How to make regex case insensitive in Rust?
- How to use captures_iter with regex in Rust?
- How to use regex captures in Rust?
- How to use regex with bytes in Rust?
- Hashshet example in Rust
See more codes...