matlab - check if variable exists in the workspace with cellfun -
consider next example:
dat1 = 1; dat2 = 2; variables = {'dat1','dat2'}; = cellfun(@(x)exist(x,'var'),variables); = 1:length(variables); a2(i) = exist(variables{i},'var'); end
why 'a' , 'a2' homecoming different values i.e. why using cellfun not state variables exist in workspace? missing?
ok, think understand what's going on here:
when phone call anonymous function, creates own workspace, normal function. however, new workspace not have access caller workspace.
thus
funh = @(x)exist(x,'var')
will ever homecoming 1 if supply 'x'
input (funh('x')
), since entire workspace consists of variable 'x'
.
consequently,
funh = @(x)exist('x','var')
will homecoming 1, regardless of supply input.
there 2 possible ways around that:
(1) utilize evalin
evaluate in caller's workspace
funh = @(x)evalin('caller',sprintf('exist(''%s'',''var'')',x))
(2) utilize output of whos
, , check against list of existing variables
variables = {'dat1','dat2'}; allvariables = whos; a3 = ismember(variables,{allvariables.name})
matlab exists
No comments:
Post a Comment