Selection of array elements with condition

2 visualizaciones (últimos 30 días)
Katerina F
Katerina F el 28 de Jul. de 2024
Comentada: Katerina F el 29 de Jul. de 2024
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

Respuesta aceptada

dpb
dpb el 28 de Jul. de 2024
Editada: dpb el 28 de Jul. de 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
Name Size Bytes Class Attributes A 1x8 1136 cell
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 = 1x8
-0.3368 -1.9879 -0.7264 -1.0663 -0.3587 -3.1295 -1.0865 -2.7800
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
[minA,ixA]=min(minA) % now find the min of the min's and return where it is
minA = -3.1295
ixA = 6
minC=A{ixA} % then the desired cell is the one at that location.
minC = 1x7
-1.0327 -2.4401 -3.1295 -2.8144 -2.3720 -1.5680 -0.6808
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
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.)
  1 comentario
Katerina F
Katerina F el 29 de Jul. de 2024
Thank you very much. It works. I does what I need.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Operators and Elementary Operations en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by