maximum value of numerical pattern

1 Ansicht (letzte 30 Tage)
Lloyd Sullivan
Lloyd Sullivan am 21 Aug. 2018
Kommentiert: Steven Lord am 21 Aug. 2018
Hi Everyone,
I have a problem that I'm slightly struggling with.
I have two arrays which represent the time step (A) and the corresponding iterations at each time step (B).
A = [1 1 1 2 2 2 3 3 3 3 4 4 4 4 4]
B = [1 2 3 1 2 3 1 2 3 4 1 2 3 4 5]
I would like to extract the maximum iteration (from B) for each time step (from A).
So it should look like
C = [1 2 3 4]
D = [3 3 4 5]
Any help is greatly appreciated.
Best regards,
Lloyd

Akzeptierte Antwort

Stephen23
Stephen23 am 21 Aug. 2018
>> A = [1 1 1 2 2 2 3 3 3 3 4 4 4 4 4];
>> B = [1 2 3 1 2 3 1 2 3 4 1 2 3 4 5];
>> C = unique(A)
C =
1 2 3 4
>> D = accumarray(A(:),B(:),[],@max)
D =
3
3
4
5
  4 Kommentare
Image Analyst
Image Analyst am 21 Aug. 2018
And Steve's answer does not work in the general case where the numbers in B can be anything, like even negative numbers. Try this and see:
A = [1 1 1 2 2 2 3 3 3 3 4 4 4 4 4];
B = rand(1, length(A)) - 0.5
G = findgroups(A);
results = splitapply(@max, B, G)
If you want something what works for any values of A and any values of B, regardless of sorting order or positive of negative values, it's a few more lines of code. Hint: one way is to use regionprops() in the Image Processing Toolbox.
Steven Lord
Steven Lord am 21 Aug. 2018
Image Analyst, to which of us were you referring when you said "Steve's answer"? If it was to me, the code you posted works when I try it in release R2018a.
>> rng default
>> A = [1 1 1 2 2 2 3 3 3 3 4 4 4 4 4];
>> B = rand(1, length(A)) - 0.5;
>> G = findgroups(A);
>> results = splitapply(@max, B, G);
>> [A.', B.'], results
ans =
1.0000 0.3147
1.0000 0.4058
1.0000 -0.3730
2.0000 0.4134
2.0000 0.1324
2.0000 -0.4025
3.0000 -0.2215
3.0000 0.0469
3.0000 0.4575
3.0000 0.4649
4.0000 -0.3424
4.0000 0.4706
4.0000 0.4572
4.0000 -0.0146
4.0000 0.3003
results =
0.4058 0.4134 0.4649 0.4706
Do you see different answers when you run those six lines of code? If so what release are you using?

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Adam Danz
Adam Danz am 21 Aug. 2018
Differentiate B in order to know when the count restarts. Then use the index of the restart-points to get C and D.
maxIdx = diff([B,-1])<0; % -1 needed to capture last value
C = A(maxIdx);
D = B(maxIdx);
  2 Kommentare
Adam Danz
Adam Danz am 21 Aug. 2018
Bearbeitet: Adam Danz am 21 Aug. 2018
Here's an alternative solution if speed is an issue (both of these solutions are fast but this one is faster).
Lloyd Sullivan
Lloyd Sullivan am 21 Aug. 2018
Very efficient - almost twice as fast. Thanks you Adam.

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Variables finden Sie in Help Center und File Exchange

Tags

Produkte


Version

R2016a

Community Treasure Hunt

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

Start Hunting!

Translated by