8
a={'a','aa','aaa','aaaa'}
length(a)
  4
size(a)
  1 4

How can I get the length of each element in the cell array with a single command? The desired output in the above example would be [1 2 3 4].

2 Answers 2

24
cellfun('length',a)

"apply length(x) to each element x in a".

cellfun docs.

Sign up to request clarification or add additional context in comments.

1 Comment

More 'modern' usage is to supply a function handle as the first argument, i.e. cellfun(@length, a).
0

arrayfun - Apply function to each element of array check documentation: http://www.mathworks.com/help/techdoc/ref/arrayfun.html

1 Comment

Are you really sure about ARRAYFUN in this case? You'd have to go through some contortions, i.e. arrayfun( @(c) length(c{1}), a) rather than the much simpler, and more obvious cellfun(@length, a)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.