Multiply Two Matrices With Nested Loops
Walk rows of A and columns of B with nested loops, multiply term by term and accumulate, producing the classic [[58,64],[139,154]] result.
Code
const A: [[i64; 3]; 2] = [[1, 2, 3], [4, 5, 6]];
const B: [[i64; 2]; 3] = [[7, 8], [9, 10], [11, 12]];
// C[i][j] = A 的第 i 行与 B 的第 j 列的内积;两个 matrices 尺寸必须匹配
fn multiply(a: &[[i64; 3]; 2], b: &[[i64; 2]; 3]) -> [[i64; 2]; 2] {
let mut c = [[0_i64; 2]; 2];
for (i, row) in a.iter().enumerate() {
for j in 0..b[0].len() {
// nested loops:一行乘一列,逐项相乘再累加
let mut dot = 0;
for (k, x) in row.iter().enumerate() {
dot += x * b[k][j];
}
c[i][j] = dot;
}
}
c
}
fn main() {
let c = multiply(&A, &B);
for row in &c {
println!("{row:?}");
}
}How it works
Multiply Two Matrices With Nested Loops comes down to the functions multiply and main.
Repetition is confined to for (i, row) in a.iter().enumerate() — the rest of the file is straight-line.
Using it
The main signature reads fn multiply(a: &[[i64; 3]; 2], b: &[[i64; 2]; 3]) -> [[i64; 2]; 2]
main is the driver: it invokes multiply before returning.
Key statements
for (i, row) in a.iter().enumerate() {
for j in 0..b[0].len() {
// nested loops:一行乘一列,逐项相乘再累加
let mut dot = 0;
for (k, x) in row.iter().enumerate() {
dot += x * b[k][j];
}
c[i][j] = dot;
}
}
Interactive Tools for This Topic
FAQ
- How do you run Multiply Two Matrices With Nested Loops?
- It runs as-is — treat the file as the whole program and execute it.
Report a problem with this exampleOpens a pre-filled issue on GitHub.