Consider the following example:
dat1 = 1;
dat2 = 2;
Variables = {'dat1','dat2'};
a = cellfun(@(x)exist(x,'var'),Variables);
for i = 1:length(Variables);
a2(i) = exist(Variables{i},'var');
end
why do 'a' and 'a2' return different values i.e. why does using cellfun not state that the variables exist in the workspace? what am I missing?
Ok, I think I understand what's going on here:
When you call an anonymous function, it creates its own workspace, as would any normal function. However, this new workspace will not have access to the caller workspace.
Thus
funH = @(x)exist(x,'var')
will only ever return 1 if you supply 'x'
as input (funH('x')
), since its entire workspace consists of the variable 'x'
.
Consequently,
funH = @(x)exist('x','var')
will always return 1, regardless of what you supply as input.
There are two possible ways around that:
(1) Use evalin
to evaluate in the caller's workspace
funH = @(x)evalin('caller',sprintf('exist(''%s'',''var'')',x))
(2) Use the output of whos
, and check against the list of existing variables
Variables = {'dat1','dat2'};
allVariables = whos;
a3 = ismember(Variables,{allVariables.name})