Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swap rows which take effect only on the under diagonal elements

Tags:

matrix

matlab

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 .

like image 458
URL87 Avatar asked May 29 '13 13:05

URL87


2 Answers

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.

like image 178
Stewie Griffin Avatar answered Sep 20 '22 19:09

Stewie Griffin


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 :) 
like image 32
Rody Oldenhuis Avatar answered Sep 18 '22 19:09

Rody Oldenhuis