问题描述
在茎图上,如何添加具有相同x
值但具有不同y
值的点?
On a stem plot, how can I add points that have the same values of x
but different values of y
?
例如,给出以下代码:
x = [1 2 3 6 6 4 5];
y = [3 6 1 8 9 4 2];
stem(x,y);
如果绘制x
和y
,则将是输出:
If you plot x
, and y
, this will be the output:
我想将(6,8)
和(6,9)
加起来,使其变成(6,17)
,就像图像显示的一样.
I want to add up (6,8)
and (6,9)
so it becomes (6,17)
, just like what the image is showing.
我该如何实现?
推荐答案
使用 accumarray
和x
和y
,因此您可以将共享同一x
的类似条目合并或分组.对这些值进行分箱后,您可以将共享同一分箱的所有值相加.这样,我们看到对于x = 6
,我们有y = 8
和y = 9
. accumarray
允许您将共享同一x
的多个y
值组合在一起.将这些值分组之后,您便可以对同一组中的所有值应用函数,以为每个组产生最终输出.在我们的例子中,我们想对它们求和,因此我们需要使用sum
函数:
Use accumarray
with x
and y
so you can bin or group like entries together that share the same 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
. accumarray
allows you to group multiple y
values together that share the same x
. 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:
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]);
我们在X
上使用 unique
在绘制stem
图时,我们没有对X
的重复. unique
还具有排序您的x
值的行为.进行x(:)
和y(:)
是为了使您可以独立地将输入数据作为行向量或列向量. accumarray
仅接受列向量(或矩阵,但我们不会去那里),因此x(:)
和y(:)
进行操作可确保两个输入均为列向量.
We use unique
on X
so that we have no repeats for X
when plotting the stem
plot. unique
also has the behaviour of sorting your x
values. Doing x(:)
and y(:)
is so that you can make your input data either as row or column vectors independently. 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.
我们得到:
上面的代码假定x
为整数,并从1开始.如果不是,则使用unique
的第三项输出为每个数字分配一个唯一的ID,然后运行通过accumarray
.完成后,像往常一样使用accumarray
的输出:
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
. When you're done, use the output of accumarray
like normal:
[xu,~,id] = unique(x);
Z = accumarray(id, y(:), [], @sum);
stem(xu, Z);
这篇关于如何将x的值相同但y的值不同的两个散点相加?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!