Combining duplicate entries in a data array

13 次查看(过去 30 天)
Hello,
I have two vectors x and y with corresponding data points. x is in sorted order, but may have double entries, e.g.
x = [0.1, 5, 5, 5, 14.5, 16, 16, 21];
y = [70, 8, 2, 3.5, 6, 5, 2.5, 3.3];
What I would like to do is find the double entries of x and combine the corresponding y values (by summing them up), so that
x_new = [0.1, 5, 14.5, 16, 21];
y_new = [70, 8+2+3.5, 6, 5+2.5, 3.3] = [70, 13.5, 7.5, 3.3];
However I struggle to manage this sufficiently. I have tried to use the function
[x_new, ia, ic] = unique(x);
but I don't know how to efficiently use these values further. Any ideas? :)
Thanks for your help!

采纳的回答

Stephen23
Stephen23 2018-3-14
编辑:Stephen23 2018-3-14
>> x = [0.1, 5, 5, 5, 14.5, 16, 16, 21];
>> y = [70, 8, 2, 3.5, 6, 5, 2.5, 3.3];
>> [xnew,~,idx] = unique(x);
>> ynew = accumarray(idx(:),y(:))
ynew =
70.0000
13.5000
6.0000
7.5000
3.3000
  2 个评论
Batuhan Arik
Batuhan Arik 2021-10-7
Hello, did the exact same thing, it seems to be working. I get x_new and y_new as they are supposed to come out. However, when I try
bar(x_new,y_new);
the plot comes out empty.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Shifting and Sorting Matrices 的更多信息

产品

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by