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?
source to share
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!
source to share
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]
source to share