0

I have a matrix A. Suppose it is:

A=[1 0 8; 
   0 0 2; 
   3 0 5; 
   4 8 0; 
   0 5 3;
   6 1 3;
   1 6 5;
   0 7 1] 

and I want to get the non-zero rows subscripts per column in a new matrix.
In my example that will be,

B = [ 1 3 4 6 7 0 0 0; 
      4 5 6 7 8 0 0 0; 
      1 2 3 5 6 7 8 0] 

In terms of just size, if A=(m,n), B will be B=(n,m) (the transpose). In terms of content, B contains the subscripts of the non-zero rows in A as described above.

chappjc
  • 30,359
  • 6
  • 75
  • 132

2 Answers2

2

Here is one way:

mask = ~sort(~A);     %// destination of row indexes in output
[ii,~]=find(A);       %// get the row indexes
B = zeros(size(A));
B(mask) = ii; B=B.'   %'//write indexes to output and transpose
chappjc
  • 30,359
  • 6
  • 75
  • 132
1

I think this does what you want (get the non-zero row indices per column). It's very similar to this other question:

[r c] = size(A);
M = bsxfun(@times, A~=0, 1:size(A,2)).'; %'// substitute values by indices
[~, rows] = sort(M~=0,'descend'); %//'' push zeros to the end
cols = repmat(1:r,c,1);
ind = sub2ind([c r],rows(:),cols(:));
B = repmat(NaN,c,r);
B(:) = M(ind).';
B = B.';

Result:

>> B

B =

     1     3     4     6     7     0     0     0
     4     5     6     7     8     0     0     0
     1     2     3     5     6     7     8     0
Community
  • 1
  • 1
Luis Mendo
  • 110,752
  • 13
  • 76
  • 147
  • 1
    Wowzers, that was quite a showing in that question you referenced! It was before my time at SO, sadly. Anyway, I'd agree with TryHard that your answer is indeed "inspiring in its elegance". ;) +1 – chappjc Dec 05 '13 at 19:36
  • @chappjc Very nice words! Thanks! It was one of my first answers; it's taken me quite a while to find it now :-) – Luis Mendo Dec 05 '13 at 19:38
  • 1
    Hmm, I like the `//` commenting workaround for SO's poor MATLAB formatting, although a `'` still messes with it. – chappjc Dec 05 '13 at 19:45
  • @chappjc So is it the `'` that spoils it? I noticed that it gets wrong sometimes, but I never knew exactly what it was. – Luis Mendo Dec 05 '13 at 19:47
  • Yeah, ever notice an extra `'` in my comments after a line of code (actually, see my current answer)? That's to trick the highlighting into stopping the string color. – chappjc Dec 05 '13 at 19:48
  • Yes, just noticed that up here! Good to know! – Luis Mendo Dec 05 '13 at 19:49
  • @chappjc Looks like the number of `'` has to balance that to the left of the `%` – Luis Mendo Dec 05 '13 at 19:54