Swapping rows and columns

后端 未结 2 1666
悲&欢浪女
悲&欢浪女 2021-02-05 16:48

I need a MATLAB function that will swap 2 rows or 2 Columns with each other in a matrix of arbitrary size.

2条回答
  •  萌比男神i
    2021-02-05 17:18

    This function only works for 2 dimensional arrays:

    function matrix = swap(matrix,dimension,idx_a,idx_b)
    
    if dimension == 1
        row_a = matrix(idx_a,:);
        matrix(idx_a,:) = matrix(idx_b,:);
        matrix(idx_b,:) = row_a;
    elseif dimension == 2
        col_a = matrix(:,idx_a);
        matrix(:,idx_a) = matrix(:,idx_b);
        matrix(:,idx_b) = col_a;
    end
    

    Example Call:

    >> A = rand(6,4)
    
    A =
    
    0.8350    0.5118    0.9521    0.9971
    0.1451    0.3924    0.7474    0.3411
    0.7925    0.8676    0.7001    0.0926
    0.4749    0.4040    0.1845    0.5406
    0.1285    0.0483    0.5188    0.2462
    0.2990    0.6438    0.1442    0.2940
    
    >> swap(A,2,1,3)
    
    ans =
    
    0.9521    0.5118    0.8350    0.9971
    0.7474    0.3924    0.1451    0.3411
    0.7001    0.8676    0.7925    0.0926
    0.1845    0.4040    0.4749    0.5406
    0.5188    0.0483    0.1285    0.2462
    0.1442    0.6438    0.2990    0.2940
    
    >> tic;A = swap(rand(1000),1,132,234);toc;
    Elapsed time is 0.027228 seconds.
    >> 
    

提交回复
热议问题