[英]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: 如果绘制x
和y
,则将是输出:
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
. 将accumarray
与x
和y
一起使用,以便可以将共享相同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 = 8
和y = 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.