Multiply elements in second column according to labels in the first

后端 未结 3 760
情歌与酒
情歌与酒 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:42

    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]
    

提交回复
热议问题