Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check if variable exists in the workspace with cellfun

Tags:

exists

matlab

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?

like image 492
KatyB Avatar asked Feb 07 '13 22:02

KatyB


2 Answers

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})
like image 130
Jonas Avatar answered Oct 31 '22 17:10

Jonas


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...

like image 37
bla Avatar answered Oct 31 '22 18:10

bla