Change strings that take effect only on sub-diagonal elements

Having a square matrix A , and I want to swap it for two lines, but with the restriction that this exchange will only affect elements that are under the diagonal in both rows.

Example -

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

swap betwen row1 and row2 will return the same matrix, because there are no elements that are below the diagonal in row 1.

but the exchange between row2 and row3 will give -

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

which actually exchanges only between 2 indices (3,1) and (2,1), because in line 2 there are no more elements under the diagonal.

How to get this function without an explicit loop, given the two required row indexes?

Here you can find a regular swap.

+6
source share
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. If necessary, you can simply use min and / or max to find the smallest / largest.

+6
source

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 :) 
+4
source

Source: https://habr.com/ru/post/946088/


All Articles