Multiply elements in second column according to labels in the first

后端 未结 3 764
情歌与酒
情歌与酒 2020-12-21 06:49

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 mult

3条回答
  •  难免孤独
    2020-12-21 07:52

    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!

提交回复
热议问题