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

5 次查看(过去 30 天)
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 个评论
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 CenterFile Exchange 中查找有关 Shifting and Sorting Matrices 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by