根据在第一标签乘以第二列元素 [英] Multiply elements in second column according to labels in the first

查看:118
本文介绍了根据在第一标签乘以第二列元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Matlab工作。
我有两列的二维矩阵。让我们考虑在第一列作为标记元素。标签可以重复。

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?

例如:

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

我需要:

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

您可以帮我做这件事的没有 换,而周期?

Can you help me with doing it without for-while cycles?

推荐答案

您可以不用使用的 accumarray 功能:

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

检查劳伦博客的帖子这里,accumarray相当有趣而强大!

Check Lauren blog's post here, accumarray is quite interesting and powerful!

这篇关于根据在第一标签乘以第二列元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆