maximum value of numerical pattern

1 vue (au cours des 30 derniers jours)
Lloyd Sullivan
Lloyd Sullivan le 21 Août 2018
Commenté : Steven Lord le 21 Août 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

Réponse acceptée

Stephen23
Stephen23 le 21 Août 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 commentaires
Image Analyst
Image Analyst le 21 Août 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 le 21 Août 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?

Connectez-vous pour commenter.

Plus de réponses (1)

Adam Danz
Adam Danz le 21 Août 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 commentaires
Adam Danz
Adam Danz le 21 Août 2018
Modifié(e) : Adam Danz le 21 Août 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 le 21 Août 2018
Very efficient - almost twice as fast. Thanks you Adam.

Connectez-vous pour commenter.

Catégories

En savoir plus sur Variables dans Help Center et File Exchange

Tags

Produits


Version

R2016a

Community Treasure Hunt

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

Start Hunting!

Translated by