Transpose matrix, pass-by-reference to function

To transpose a matrix in Rust and pass it by reference to a function, you can follow these steps:

  1. Define a function that takes a reference to a matrix as a parameter.
  2. Inside the function, create a new matrix with the dimensions swapped (i.e., the number of rows becomes the number of columns, and vice versa).
  3. Use nested loops to iterate over the elements of the original matrix and assign them to the corresponding positions in the transposed matrix.
  4. Return the transposed matrix.

Here's an example implementation:

fn transpose_matrix(matrix: &Vec<Vec<i32>>) -> Vec<Vec<i32>> {
    let rows = matrix.len();
    let cols = matrix[0].len();

    let mut transposed = vec![vec![0; rows]; cols];

    for i in 0..rows {
        for j in 0..cols {
            transposed[j][i] = matrix[i][j];
        }
    }

    transposed
}

To use this function, you can create a matrix and pass it by reference to the transpose_matrix function. Here's an example:

fn main() {
    let matrix = vec![
        vec![1, 2, 3],
        vec![4, 5, 6],
        vec![7, 8, 9],
    ];

    let transposed = transpose_matrix(&matrix);

    println!("Original matrix: {:?}", matrix);
    println!("Transposed matrix: {:?}", transposed);
}

This will output:

Original matrix: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Transposed matrix: [[1, 4, 7], [2, 5, 8], [3, 6, 9]]

I hope this helps! Let me know if you have any further questions.