Given a cell array, find the longest string
12 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Preferably without using loops, I need to find the longest string in a cell array. So with an example array such as the following, in what ways could I go about this? If there are multiple entries with the same length, I need to be able to find both of them.
I'd like to see a way to do it with loops as well.
Pete Townshend Toyota Gene Simmons Steve Jobs Socrates Frank Sinatra Astronomy Idaho Sweatshirt
Thanks
0 Kommentare
Akzeptierte Antwort
Azzi Abdelmalek
am 15 Feb. 2013
Bearbeitet: Azzi Abdelmalek
am 15 Feb. 2013
a={'Pete' 'Townshend1' 'Simmons' 'Steve' 'Sinatra' 'Idaho' 'Sweatshirt'}
val=cellfun(@(x) numel(x),a)
out=a(val==max(val))
%With a loop
for k=1:numel(a)
val(k)=numel(a{k})
end
out=a(val==max(val))
1 Kommentar
Jan
am 15 Feb. 2013
Bearbeitet: Jan
am 15 Feb. 2013
cellfun('length', a) is much more efficient, because the string methods of cellfun() are determined inside the MEX function, while the anonymous functions need to call Matlab for each argument. Unfortunately these string methods are marked as "backward compatibility" feature only in the documentation, but this is an understatement.
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!