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 convert a Rust HashMap to a BTreeMap?
- How to use regex to match a group in Rust?
- How to use non-capturing groups in Rust regex?
- How to match a URL with a regex in Rust?
- How to use the global flag in a Rust regex?
- How to match digits with regex in Rust?
- How to use regex to match a double quote in Rust?
- How to create a HashSet from a Vec in Rust?
- How to print the keys of a Rust HashMap?
- How to implement PartialEq for a Rust HashMap?
See more codes...