3

I am extremely new to the matlab programming language and am trying to accomplish the following task:

   (1,3)       0.0000
   (2,3)       0.0000
   (3,3)       0.0000
   (4,3)       0.4803
   (5,3)       0.0000
   (6,3)       0.0000
   (7,3)       0.0000
   (8,3)       0.0000
   (9,3)       0.0030
  (10,3)       0.0000
  (11,3)       0.0000

The above matrix is a sparse column vector (only a part of which is shown above) of values most of which are zero. I would like to get the indices of the values sorted in descending order which would basically give me the positive non-zero values (there are no negative values in the vector!) in descending order along with their corresponding indices. I would like to know how to achieve this in matlab. I tried the sort function in matlab and it seems to sort the values but doesn't keep track of the indices which are also equally crucial. I also looked at sortrows function but doesn't seem to work for me. I tried the following code which was from another question at SO (unfortunately I am unable to find it again in order to cite it here):

A = sparse([0,1,2;3,4,5;6,7,8])
[sortValues,sortIndex] = sort(A(:),'descend');

Output:

sortValues =

   (1,1)        8
   (2,1)        7
   (3,1)        6
   (4,1)        5
   (5,1)        4
   (6,1)        3
   (7,1)        2
   (8,1)        1 

    sortIndex =

         9
         6
         3
         8
         5
         2
         7
         4
         1

In this case I don't know how to make use of the sortIndex to retrieve the original indices of the sorted values. Any help would be much appreciated.

Just to be clear the output that I am looking for in the above case of the sparse matrix would be:

(4,3)     0.4803
(9,3)     0.0030
........  0.0000
........  0.0000
........  0.0000
etc...

1 Answer 1

2
 [I,J,S]=find(A);

 result=sortrows([I,J,S],-3);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.