Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

To resolve issues starting MATLAB on Mac OS X 10.10 (Yosemite) visit: http://www.mathworks.com/matlabcentral/answers/159016

Finding unique rows in a matrix and summing their weights faster

Asked by Kristofer Kusano on 24 Jun 2013

I am performing the following:

    % a matrix where rows are observations
    A = [1 2;
         4 6;
         1 2;
         9 2;
         4 2;
         6 9];
    % each row has a weight
    W = (1:size(A, 1))';
    % find unique rows
    [uA, ~, icA] = unique(A, 'rows')
    >> 
    uA =
         1     2
         4     2
         4     6
         6     9
         9     2
    icA =
         1
         3
         1
         5
         2
         4
    % what is the combined weight for each unique row?
    wA = zeros(size(uA, 1), 1);
    for i = 1:length(uA)
        wA(i) = sum(W(icA == i));
    end
    % check it works
    wA
    >>
    wA =
         4
         5
         2
         6
         4
    assert(sum(W) == sum(wA), 'sum(W) ~= sum(wA)') 

The code works, but the for loop is very slow for a large number of rows. Does anyone know a faster way to do this?

0 Comments

Kristofer Kusano

Products

No products are associated with this question.

1 Answer

Answer by Andrei Bobrov on 24 Jun 2013
Edited by Andrei Bobrov on 24 Jun 2013
Accepted answer
A = [1 2
4 6
1 2
9 2
4 2
6 9];
[aa,cc,cc] = unique(A,'rows');
W = (1:size(A, 1))';
wA = accumarray(cc,W);

0 Comments

Andrei Bobrov

Contact us