2
votes

I have a matrix like

A = [ 0 1 1;0 0 0;1 1 0]

For this, I wish to know indices of 1's in such a manner that:

For row 1, I need values of indices of column where its coming equal 1. Similarly for row 2 and row 3.

Later, I want to repeat this exercise for column, like for column 1, I need the value of indices of rows where its coming equal to 1. and similarly for column 2 and column 3.

The ans should be like this :

  • for row 1 - indices are: 2,3
  • for row 2 - indices are: 0
  • for row 3 - indices are: 1,2

Similarly:

  • for column 1 - indices are: 3
  • for column 2 - indices are: 1,3
  • for column 3 - indices are: 1

Please help.

2

2 Answers

3
votes

Use find and accumarray:

[ii jj] = find(A); %// find row and col indices (ii and jj respectively)
rows = accumarray(ii,jj,[], @(v) {sort(v).'}); %'// group jj as per ii, and sort
cols = accumarray(jj,ii,[], @(v) {sort(v).'}); %'// group ii as per jj, and sort

For your example, this gives

>> rows{:}
ans =
     2     3
ans =
     []
ans =
     1     2
>> cols{:}
ans =
     3
ans =
     1     3
ans =
     1

If you really need to fill empty results with a 0:

rows = accumarray(ii,jj,[], @(v) {sort(v).'}, {0}); %'// 5th input is fill value
cols = accumarray(jj,ii,[], @(v) {sort(v).'}, {0});

which results in

>> rows{:}
ans =
     2     3
ans =
     0
ans =
     1     2
>> cols{:}
ans =
     3
ans =
     1     3
ans =
     1
0
votes

The simplest way is probably to use loops and the find function combined with a cell array to store your answer. For example, to get list of the ones in each row:

for i=1:size(A,1)
    rowsOne{i} = find(A(i,:)==1);
end

rowsOne{i} then contains a vector listing the indices of the elements in row i of array A that equal one. If there are no elements that equal 1 in a row, it will hold an empty array.

The solution for the columns is roughly the same.