Find the index of the element of a cell array which has the maximum size

6 ビュー (過去 30 日間)
AP
AP 2011 年 6 月 4 日
編集済み: Jan 2017 年 10 月 27 日
I have a cell array (B) which has elements having two columns and different number of rows. I want to find the element which has the largest number of rows. I wrote the following code which seems to me non-professional. Is there a better way to do that?
max_index=0;
max_size=0;
for i=1:numel(B)
if max_size<size(B{i},1)
max_size=size(B{i},1);
max_index=i;
end
end
Thanks.

採用された回答

Jan
Jan 2011 年 6 月 4 日
[max_size, max_index] = max(cellfun('size', B, 1))
  2 件のコメント
huahua
huahua 2017 年 10 月 26 日
What if I want the cell of second largest size?
Jan
Jan 2017 年 10 月 27 日
編集済み: Jan 2017 年 10 月 27 日
@huahua:
siz = cellfun('size', B, 1);
[~, idx] = max(siz);
siz(idx) = -Inf;
[size2, index2] = max(siz);
This is cheaper than sorting.

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

その他の回答 (1 件)

Jos (10584)
Jos (10584) 2017 年 10 月 26 日
NrowsB = cellfun('size',B,1) ;
[~, ri] = sort(NrowsB)
ri(k) % index of B with the k-th most number of rows

カテゴリ

Help Center および File ExchangeMATLAB についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by