what are the differences between [] and '' in a cell array, how to identify and differentiate them?

1 view (last 30 days)
c1={'a',[],'b'}-->
isempty(c1(2))=0; Not empty
size(c(2))=1 1;
strcmp(c(2),[])=0; Not a string
c2={'a','','b'}-->
isempty(c2(2))=0; Not empty
size(c(2))=1 1;
strcmp(c(2),'')=1; Is a string
So I can use strcmp(c,'')==1 to find ''. But how about []?
Thanks...

Accepted Answer

Walter Roberson
Walter Roberson on 1 Oct 2013
isempty(c1{2})
Notice the {} instead of ()

More Answers (1)

Jan
Jan on 1 Oct 2013
In isempty(c1(2)), the expression c1(2) is equivalent to: {[]}, which is a 1x1 cell. This cell contains 1 element and is not empty in consequence. But you want to test the element of the cell. As Walter has pointed out this requires the curly braces: c1{2} is the 2nd element of the cell array, which is the empty matrix.
This might be helpful:
c = {'1', 2, '', []}
emptyC = cellfun('isempty', c)
charC = cellfun('isclass', c, 'char')
emptyC & charC
emptyC & ~charC
Alternatively: cellfun(@isempty, c) and cellfun(@ischar, c), but this is a little bit slower.
  3 Comments
Jan
Jan on 2 Oct 2013
@J.Hu: When the function to be applied is defined by a string, the job is performed directly in the MEX file. When a function handle is provided, cellfun calls this command by mexCallMATLAB for each element, which causes a noticeable overhead. This is even worse for anonymous functions, e.g. : cellfun(@(x) isempty(x), c).
Older versions of Matlab contains the source code cellfun.c of this command, such that this behavior could be understood easily. Unfortunately in modern Matlab versions, you can not read the source code and the very efficient string commands appear under the term "Backward compatibility" in the documentation only.

Sign in to comment.

Categories

Find more on Cell Arrays in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!