6
votes

Having square matrix A and I want to swap between 2 row on it , but with constraint that this swap would take effect only on the elements which are under the diagonal in both row .

Example -

1 2 3 4
3 6 7 8 
6 5 4 2
9 4 6 7

swap betwen row1 and row2 would return same matrix because there is no elements which are under the diagonal in row 1 .

but swap between row2 and row3 would give -

1 2 3 4
6 6 7 8 
3 5 4 2
9 4 6 7

which actually swapped just between 2 element index (3,1) and (2,1) because there is no more elements in row2 which are under to diagonal .

How to obtain this function with no explicit loop by given the two required row indexes ?

Regular swap could be found here .

2

2 Answers

6
votes

You can try the following:

A([row1 row2],1:row1-1) = A([row2 row1],1:row1-1)

Note that row1 <= row2 for this to work. If necessary, you can simply use min and / or max to find which is smallest / largest.

4
votes

This should do the trick:

function A = swapRowsBelowDiagonal(A, a,b)

    m = min(a,b)-1;
    [A(a,1:m), A(b,1:m)] = swap(A(a,1:m), A(b,1:m));
end

function [y,x] = swap(x,y), end % NOTE: no body, just for fun :)