svdc
svdc

Reputation: 164

Finding the column indices of submatrices in MATLAB

Suppose I have the following matrix

 1     1     0     0     0
 1     1     0     0     0
 0     0     1     1     1
 0     0     1     1     1
 0     0     1     1     1

The result would be

{[1,2],[3,4,5]}

How would I implement this?

I have an ugly solution involving a loop that runs through the diagonal (except (1,1)) and checks whether the element directly left is 0. If not, that is the start of a new cluster.

Is there a prettier solution?

EDIT: current solution:

n = size(input, 2);
result = cell(1,n);
result{1} = 1;
counter = 1;
for i = 2:n
    if input(i,i-1) ~= 1
        counter = counter + 1;
    end
    result{counter} = [result{counter} i];
end
result =  result(~cellfun('isempty',result));

Upvotes: 1

Views: 72

Answers (1)

Shai
Shai

Reputation: 114976

use unique with 'rows' argument on the matrix transposed

Upvotes: 2

Related Questions