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

9 次查看(过去 30 天)
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...

采纳的回答

Walter Roberson
Walter Roberson 2013-10-1
isempty(c1{2})
Notice the {} instead of ()

更多回答(1 个)

Jan
Jan 2013-10-1
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 个评论
Jan
Jan 2013-10-2
@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.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 App Building 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by