accumarray function for equal integer values

10 views (last 30 days)
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!

Accepted Answer

Bruno Luong
Bruno Luong on 16 Nov 2018
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 Comment
Stephen23
Stephen23 on 16 Nov 2018
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

Sign in to comment.

More Answers (1)

Andrei Bobrov
Andrei Bobrov on 16 Nov 2018
Edited: Andrei Bobrov on 16 Nov 2018
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');

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!