Multiply the elements in the second column according to the labels in the first

I am working in Matlab. I have a 2-column matrix. Let's consider the items in the first column as labels. Labels can be repeated.

How do I multiply all the elements in the second column for each label?

Example:

matrix = [1,3,3,1,5; 2,3,7,8,3]'

      

I need to get:

a = [1,3,5; 16,21,3]'

      

Can you help me to do this without for-while

loops?

+3


source to share


3 answers


You can do it without loops using accumarray and prod

:

clear
clc


matrix = [1,3,3,1,5; 2,3,7,8,3]';

A = unique(matrix,'rows');

group = A(:,1);

data = A(:,2);

indices = [group ones(size(group))];

prods = accumarray(indices, data,[],@prod); %// As mentionned by @Daniel. My previous answer had a function handle but there is no need for that here since prod is already defined in Matlab.

a = nonzeros(prods)

Out = [unique(group) a]

Out =

     1    16
     3    21
     5     3

      



Check out Lauren's blog post here , the drive is pretty interesting and powerful!

+4


source


I would use accumarray

. The preprocessing with unique

assigns integer indices 1: n to the values ​​in the first line, which allows you accumarray

to work without creating unnecessary bins for 2 and 4. It also supports negative numbers and floats.



[ulable,~,uindex]=unique(matrix(:,1))
r=accumarray(uindex,matrix(:,2),[],@prod)
r=[ulable,r]

      

+7


source


Try something like this, I'm sure it can be improved ...

unValues = unique(matrix(:,1));
bb = ones(size(unValues));

for ii = 1:length(unValues)
    bb(ii) = bb(ii)*prod(matrix(matrix(:, 1) == unValues(ii), 2));
end

a = [unValues bb];

      

+1


source







All Articles