Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiply elements in second column according to labels in the first

I'm working in Matlab. I have a two-dimensional matrix with two columns. Lets consider elements in the first column as labels. Labels may be repeated.

How to multiply all elements in the second column for every 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 with doing it without for-while cycles?

like image 701
Macaronnos Avatar asked Dec 30 '25 05:12

Macaronnos


2 Answers

I would use accumarray. The preprocessing with unique assigns integer indices 1:n to the values in the first row, which allow accumarray to work without creating unnecessary bins for 2 and 4. It also enables the support for negative numbers and floats.

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

/You can also use splitapply:

[ulable,~,uindex]=unique(matrix(:,1))
r=splitapply(@prod,matrix(:,2),uindex)
r=[ulable,r]
like image 153
Daniel Avatar answered Dec 31 '25 17:12

Daniel


You can do it without loops using accumarray and the prod function:

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 Lauren blog's post here, accumarray is quite interesting and powerful!

like image 36
Benoit_11 Avatar answered Dec 31 '25 18:12

Benoit_11