On a stem plot, how can I add points that have the same values of x
but different values of 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:
I want to add up (6,8)
and (6,9)
so it becomes (6,17)
, just like what the image is showing.
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
. 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]);
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.
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
. When you're done, use the output of accumarray
like normal:
[xu,~,id] = unique(x);
Z = accumarray(id, y(:), [], @sum);
stem(xu, Z);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.