Guilherme
Guilherme

Reputation: 55

Count number of rows in a matrix - Matlab

I have been looking for quite a while now, but I still didn't find a way of counting rows of a matrix in a efficient way. There are some solutions out there, but none of them find my needs. The code above does the job, but takes too much time if your dealing with a big matrix. The output that I would like to have is the one just like the variable cont2, that is, a vector with length equal to the number of rows in A. Here is an example:

    A = [ 1 2 3 ; 4 3 5; 1 2 3; 1 2 3; 4 3 5; 5 2 1; 3 2 1; 3 5 1];

    [rows,~] = size(A);
    cont2 = zeros(rows,1,'single');

    for i = 1:rows
        cont = 0;
        for j = 1:rows

            if A(i,:) == A(j,:)
                cont = cont + 1;
            end

            cont2(i) = cont;
        end
    end

%Result: cont2 =

     3
     2
     3
     3
     2
     1
     1
     1

Upvotes: 3

Views: 168

Answers (1)

Luis Mendo
Luis Mendo

Reputation: 112659

How about some bsxfun?

result = sum(all(bsxfun(@eq, A, permute(A, [3 2 1])), 2), 3);

This compares each row with each other, and sums the number of matchings to produce the desired result.


Equivalently, you can reduce each row to a unique integer label using unique, and then compare those labels:

[~, ~, u] = unique(A, 'rows');
result = sum(bsxfun(@eq, u, u.'), 2);

Or use histc to count how many times each label appears:

[~, ~, u] = unique(A, 'rows');
c = histc(u, 1:max(u));
result = c(u);

Upvotes: 4

Related Questions