accumarray function for equal integer values

13 次查看(过去 30 天)
Hey guys,
I have a question about the accumarray function.
I have a table containing columns B1 and B2. B1= [34.1; 34.2; 35.6; 35.7] and B2 shows corresponding intensities and is [600; 800; 200; 100] respectively. My first step is rounding the B1 values to a nominal value, resulting in B1 = [34; 34; 36; 36]. However, in the second step I would like to use the accumarray function for B1 and B2, but this only gives the accumulated B2 column, B2 = [1400; 300]. I would also like to see the B1 column in which duplicate nominal values are now single values. Thus, B1 = [34; 36].
accumarray.png
many thanks!

采纳的回答

Bruno Luong
Bruno Luong 2018-11-16
B1 = [34.1; 34.2; 35.6; 35.7];
B2 = [600; 800; 200; 100];
Br1 = round(B1);
u = unique(Br1);
[~,J] = ismember(Br1, u);
B2s = accumarray(J(:),B2);
s = [u B2s];
s(J,:)
  1 个评论
Stephen23
Stephen23 2018-11-16
Felix Flores James's "Answer" moved here and formatted properly:
Bruno,
Thank you for your answer. You're completely right, I should post data/code so that you guys can easily copy and past it in MATLAB. I will do that from now on.
It worked! Thank you!
>> B1 = [34.1; 34.2; 35.6; 35.7];
B2 = [600; 800; 200; 100];
Br1 = round(B1);
u = unique(Br1);
[~,J] = ismember(Br1, u);
B2s = accumarray(J(:),B2);
s = [u B2s];
s(J,:);
>> C = [u B2s]
C =
34 1400
36 300

请先登录,再进行评论。

更多回答(1 个)

Andrei Bobrov
Andrei Bobrov 2018-11-16
编辑:Andrei Bobrov 2018-11-16
B1 = [34.1; 34.2; 35.6; 35.7];
B2 = [600; 800; 200; 100];
B = table(B1,B2);
B.B1 = round(B.B1);
Bnew = varfun(@sum,B,'GroupingVariables','B1');

类别

Help CenterFile Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by