Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,239 questions

56,142 answers

573 users

How to inverse N x M matrix in Rust

1 Answer

0 votes
fn print_matrix(matrix: &Vec<Vec<i32>>) {
    for row in matrix {
        for val in row {
            // pad each number to width 4
            print!("{:4}", val);
        }
        println!();
    }
}

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

    let mut r = rows - 1;
    for i in 0..rows {
        let mut c = cols - 1;
        for j in 0..cols {
            // swap values
            let tmp = matrix[i][j];
            matrix[i][j] = matrix[r][c];
            matrix[r][c] = tmp;

            counter += 1;
            if counter > (rows * cols) / 2 - 1 {
                return;
            }
            if c > 0 { c -= 1; }
        }
        if r > 0 { r -= 1; }
    }
}

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

    println!("matrix:");
    print_matrix(&matrix);

    inverse_matrix(&mut matrix);

    println!("\ninverse matrix:");
    print_matrix(&matrix);
}



/*
run:

matrix:
   1   2   3   4
   5   6   7   8
   9  10  11  12

inverse matrix:
  12  11  10   9
   8   7   6   5
   4   3   2   1

*/

 



answered Nov 23, 2025 by avibootz

Related questions

...