Selection of array elements with condition

2 ビュー (過去 30 日間)
Katerina F
Katerina F 2024 年 7 月 28 日
コメント済み: Katerina F 2024 年 7 月 29 日
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

採用された回答

dpb
dpb 2024 年 7 月 28 日
編集済み: dpb 2024 年 7 月 28 日
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 件のコメント
Katerina F
Katerina F 2024 年 7 月 29 日
Thank you very much. It works. I does what I need.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeOperators and Elementary Operations についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by