How do I replace same values in an array?

If I have this couples of values: 1—5; 2—7; 3—4; 2—3; 6—5 and I want that the first column is the x column and the second one is the y column of an xy graph (especially an histogram), how can I make that for the same value of x, y is the sum of y values for the same x as follow? 1—5; 2—10; 3—4; 6—5.
Thank you
Fabio

 採用された回答

dpb
dpb 2014 年 5 月 20 日

0 投票

If
xy=your array;
y=accumarray(xy(:,1),xy(:,2));
See
doc unique
doc accumarray
for how the above works...
>> xy=[1 5;2 4;3 8; 2 6];
>> [unique(xy(:,1)) accumarray(xy(:,1),xy(:,2))]
ans =
1 5
2 10
3 8

4 件のコメント

Fabio
Fabio 2014 年 5 月 21 日
Thank you dpb.
Fabio
Fabio
Fabio 2014 年 5 月 21 日
編集済み: Fabio 2014 年 5 月 21 日
There is a problem when the first column values aren't continuos, for example for xy=[1 2; 2 3; 3 4; 2 7; 8 1]. so to avoid error, that's the correct way:
xy=[1 2; 2 3; 3 4; 2 7; 8 1];
ac=accumarray(xy(:,1),xy(:,2))
ac_modified=ac(ac~=0); % to delete zeros
result= [unique(xy(:,1)) ac_modified]
dpb
dpb 2014 年 5 月 21 日
Or in place without a temporary,
ac(ac==0)=[]; % to delete zeros
You can also get more clever in using unique and accumarray together with the alternate outputs of unique as indices and anonymous functions to only sum the nonzero entities. I'll leave as "exercise for the student"; the nuances of accumarray are legion and an area of expertise to be gained all of its own. :)
Fabio
Fabio 2014 年 5 月 22 日
Thank you again :)

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeData Distribution Plots についてさらに検索

製品

質問済み:

2014 年 5 月 20 日

コメント済み:

2014 年 5 月 22 日

Community Treasure Hunt

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

Start Hunting!

Translated by