Selection of array elements with condition
2 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
I have a 1×294 cell array. For simplicity I show here a shorter verion of this, 1x8
A={[-0.3368 -0.0329]}
{ [-0.5666 -1.2306 -1.9879 -1.6091 -1.0889 -0.6703]} {[-0.5950 -0.7264 -0.2151]} {[ -0.3346 -0.8525 -1.0663 -0.7172 -0.3690 ]} {[-0.3587 -0.2960]}
{[-1.0327 -2.4401 -3.1295 -2.8144 -2.3720 -1.5680 -0.6808]} {[-0.3728 -1.0863 -1.0865 -0.6916 -0.4153 -0.0177]} {[-0.3969 -1.2583 -1.9764 -2.7800 -2.4100 -1.6038 -0.4912]}
I want to write a code so that I select the array that contains the smallest number, in this case the smallest is -3.1295. So I would like that the answer is
[-1.0327 -2.4401 -3.1295 -2.8144 -2.3720 -1.5680 -0.6808]
Could you please help me with this? I tried this: A(cellfun(@(x) all(all(x==-0.3749)),A)) but it gives me an empty array. Thank you
0 commentaires
Réponse acceptée
dpb
le 28 Juil 2024
Modifié(e) : dpb
le 28 Juil 2024
A=[{[-0.3368 -0.0329]} ...
{ [-0.5666 -1.2306 -1.9879 -1.6091 -1.0889 -0.6703]} {[-0.5950 -0.7264 -0.2151]} {[ -0.3346 -0.8525 -1.0663 -0.7172 -0.3690 ]} {[-0.3587 -0.2960]} ...
{[-1.0327 -2.4401 -3.1295 -2.8144 -2.3720 -1.5680 -0.6808]} {[-0.3728 -1.0863 -1.0865 -0.6916 -0.4153 -0.0177]} {[-0.3969 -1.2583 -1.9764 -2.7800 -2.4100 -1.6038 -0.4912]}];
whos A
Actually, it's 1x8 but who's counting??? :)
You were on the right track, but matching floating point with "==" is risky. Since you have a cell array with differently sized cells, rearranging into a regular 2D array and doing min by column doesn't work without a lot of additional effort.
So
minA=cellfun(@min,A) % go ahead and find the min of each
[minA,ixA]=min(minA) % now find the min of the min's and return where it is
minC=A{ixA} % then the desired cell is the one at that location.
NOTA BENE: If there might be a need for the other minima, you can "have your cake and eat it, too!"
[~,ixA]=min(minA) % now find the min of the min's and return ONLY where it is
The above would not overwrite the minA array, returning only the index of where the overall minimum is. (This must replace the above line, not follow it.)
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Operators and Elementary Operations dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!