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

6 Ansichten (letzte 30 Tage)
AP
AP am 4 Jun. 2011
Bearbeitet: Jan am 27 Okt. 2017
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.

Akzeptierte Antwort

Jan
Jan am 4 Jun. 2011
[max_size, max_index] = max(cellfun('size', B, 1))
  2 Kommentare
huahua
huahua am 26 Okt. 2017
What if I want the cell of second largest size?
Jan
Jan am 27 Okt. 2017
Bearbeitet: Jan am 27 Okt. 2017
@huahua:
siz = cellfun('size', B, 1);
[~, idx] = max(siz);
siz(idx) = -Inf;
[size2, index2] = max(siz);
This is cheaper than sorting.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

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

Kategorien

Mehr zu MATLAB finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by