what are the differences between [] and '' in a cell array, how to identify and differentiate them?
9 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
J. Hu
am 1 Okt. 2013
Kommentiert: Jan
am 2 Okt. 2013
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...
0 Kommentare
Akzeptierte Antwort
Weitere Antworten (1)
Jan
am 1 Okt. 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 Kommentare
Jan
am 2 Okt. 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.
Siehe auch
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!