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 matrixa
with elements1
,2
,3
and4
.let b = vec![vec![5, 6], vec![7, 8]];
creates a 2x2 matrixb
with elements5
,6
,7
and8
.let mut c = vec![vec![0, 0], vec![0, 0]];
creates a 2x2 matrixc
with elements0
,0
,0
and0
.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 matricesa
andb
and stores the result in matrixc
.
Helpful links
Related
More of Rust
- How to match the end of a line in a Rust regex?
- How to use regex to match a double quote in Rust?
- How to split a string with Rust regex?
- How to use regex to match a group in Rust?
- How to get a capture group using Rust regex?
- How to use regex with bytes in Rust?
- How to replace a capture group using Rust regex?
- How to perform matrix operations in Rust?
- How to parse JSON string in Rust?
- How to use a tuple as a key in a Rust HashMap?
See more codes...