accumarray function for equal integer values

1 Ansicht (letzte 30 Tage)
Felix Flores James
Felix Flores James am 16 Nov. 2018
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!

Akzeptierte Antwort

Bruno Luong
Bruno Luong am 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 Kommentar
Stephen23
Stephen23 am 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

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Andrei Bobrov
Andrei Bobrov am 16 Nov. 2018
Bearbeitet: Andrei Bobrov am 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');
  1 Kommentar
Felix Flores James
Felix Flores James am 16 Nov. 2018
Bearbeitet: Felix Flores James am 16 Nov. 2018
Thank you!
This seems even easier to use.

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Data Type Conversion finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by