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})
I think you should write the cellfun
line as:
a = cellfun(@(x) exist('x','var'),Variables);
to make it equivalent to the for loop.
See also how to use exist
in Matlab's Documentation examples...
EDIT:
After (I think I'm) understanding Jonas's answer, the line above will always return true regardless if dat1=1
or dat1=[]
. In order to use cellfun
see Jonas answer...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With