0
votes

I have an upper triangular matrix from which I need to extract the non-zero data in an increasing order and corresponding row and column numbers to use in the rest of the matlab program - can someone please suggest an efficient way to do this.

As an illustration , here is an example of a matrix that I can have :

0   16.38028519 57.19639932 109.1383791 168.7622095
0   0           12.41026354 41.10752608 80.27145093
0   0           0           8.356508551 29.60683208
0   0           0           0           6.510638154
0   0           0           0           0

I require an output :

Data         Row Num    Col Num
6.510638154         4   5
8.356508551         3   4
12.41026354         2   3
16.38028519         1   2
29.60683208         3   5
41.10752608         2   4
57.19639932         1   3
80.27145093         2   5
109.1383791         1   4
168.7622095         1   5

The size of the matrix can run into 100's - so an algorithm that is fast would make a tremendous difference.

Many Thanks for help.

2

2 Answers

2
votes

Use find to get rows, columns and values; and then sortrows to sort according to values:

[ii jj vv] = find(A); %// "A" denotes your matrix
result = sortrows([vv ii jj], 1); %// "1" to sort rows according to column 1
0
votes

There is a function called find in matlab it will return indicis of all non zero elem in matrix and the element. http://www.mathworks.com/help/matlab/ref/find.html here is an exmple with your matrix.

A = [0 16.38028519 57.19639932 109.1383791 168.7622095;0 0 12.41026354 41.10752608 

80.27145093;0 0 0 8.356508551 29.60683208;0 0 0 0 6.510638154;0 0 0 0 0];
[r,c,v] = find(A);
B(:,1) = v(:);
B(:,2) = r(:);
B(:,3) = c(:);

disp('    Data        RowNum    ColNum');
disp(sortrows(B,1) );

here is the out put:

 >> printtable
    Data        RowNum    ColNum
    6.5106    4.0000    5.0000
    8.3565    3.0000    4.0000
   12.4103    2.0000    3.0000
   16.3803    1.0000    2.0000
   29.6068    3.0000    5.0000
   41.1075    2.0000    4.0000
   57.1964    1.0000    3.0000
   80.2715    2.0000    5.0000
  109.1384    1.0000    4.0000
  168.7622    1.0000    5.0000