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

조회 수: 3 (최근 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 CenterFile Exchange에서 MATLAB에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by