Last active
March 26, 2023 16:37
-
-
Save samueleresca/d8af00ccb0bc0b6bee01098219b0961a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// # Arguments | |
/// | |
/// * `n` - The dimension of the matrix. | |
/// | |
/// # Returns a matrix with values from 0 to n - 1. | |
/// Initializes a matrix with values from 0 to n - 1. | |
pub fn generate_matrix(n: usize) -> Vec<Vec<f64>> { | |
let mut matrix = vec![vec![0.0; n]; n]; | |
let mut value = 0.0; | |
for r in 0..n { | |
for c in 0..n { | |
matrix[r][c] = value; | |
value += 1.0; | |
} | |
} | |
matrix | |
} | |
/// Returns the result of a matrix multiplication. | |
/// It transpose the second matrix to optimize the sequential memory access. | |
/// | |
/// # Arguments | |
/// | |
/// * `n` - The dimension of the matrix. | |
pub fn optimized(n: usize) -> Vec<Vec<f64>> { | |
let m1 = generate_matrix(n); | |
let m2 = m1.clone(); | |
let mut tmp = vec![vec![0.0; n]; n]; | |
let mut res = vec![vec![0.0; n]; n]; | |
// Transpose the second matrix. | |
for i in 0..n { | |
for j in 0..n { | |
tmp[i][j] = m2[j][i]; | |
} | |
} | |
// Perform the multiplication. | |
for i in 0..n { | |
for j in 0..n { | |
for k in 0..n { | |
res[i][j] += m1[i][k] * tmp[j][k]; | |
} | |
} | |
} | |
res | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment