简体   繁体   English

如何将x的值相同但y的值不同的两个散点相加?

[英]How do I add up two scatter points with the same values of x but different values of y?

On a stem plot, how can I add points that have the same values of x but different values of y ? 在茎图上,如何添加x值相同但y值不同的点?

For example, given the following code: 例如,给出以下代码:

x = [1 2 3 6 6 4 5];
y = [3 6 1 8 9 4 2];
stem(x,y);

If you plot x , and y , this will be the output: 如果绘制xy ,则将是输出:

在此处输入图片说明

I want to add up (6,8) and (6,9) so it becomes (6,17) , just like what the image is showing. 我想将(6,8)(6,9)加起来,使其变成(6,17) ,就像图像显示的一样。

How can I achieve this? 我该如何实现?

Use accumarray with x and y so you can bin or group like entries together that share the same x . accumarrayxy一起使用,以便可以将共享相同x类似条目合并或分组。 Once these values are binned, you can sum all of the values that share the same bin together. 对这些值进行分箱后,您可以将共享同一分箱的所有值相加。 As such, we see that for x = 6 , we have y = 8 and y = 9 . 这样,我们看到对于x = 6 ,我们有y = 8y = 9 accumarray allows you to group multiple y values together that share the same x . accumarray允许您将共享相同x多个y值组合在一起。 Once these values are grouped, you then apply a function to all of the values in the same group to produce a final output for each group. 将这些值分组后,您便可以对同一组中的所有值应用函数,以为每个组产生最终输出。 In our case, we want to sum them, so we need to use the sum function: 在我们的例子中,我们想对它们求和,因此我们需要使用sum函数:

x = [1 2 3 6 6 4 5];
y = [3 6 1 8 9 4 2];
Z = accumarray(x(:), y(:), [], @sum);
stem(unique(x), Z);
xlim([0 7]);

We use unique on X so that we have no repeats for X when plotting the stem plot. 我们在X上使用unique ,因此在绘制stem图时不会重复X unique also has the behaviour of sorting your x values. unique也具有对x值进行排序的行为。 Doing x(:) and y(:) is so that you can make your input data either as row or column vectors independently. 这样做x(:)y(:)是为了使您可以独立地将输入数据作为行向量或列向量。 accumarray accepts only column vectors (or matrices, but we won't go there) and so doing x(:) and y(:) ensures that both inputs are column vectors. accumarray仅接受向量(或矩阵,但我们不会去那里),因此执行x(:)y(:)可确保两个输入均为列向量。

We get: 我们得到:

在此处输入图片说明

The above code assumes that x is integer and starting at 1. If it isn't, then use the third output of unique to assign each number a unique ID, then run this through accumarray . 上面的代码假定x整数,并且从1开始。如果不是,则使用unique的第三个输出为每个数字分配一个唯一的ID,然后通过accumarray运行它。 When you're done, use the output of accumarray like normal: 完成后,像accumarray一样使用accumarray的输出:

[xu,~,id] = unique(x);
Z = accumarray(id, y(:), [], @sum);
stem(xu, Z);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM