Expanding a struct of variables

From NA-Wiki

Jump to: navigation, search
function explode(struct)
%EXPLODE  Expand a struct in the caller workspace
%   EXPLODE(STRUCT)
%
%   for each field in STRUCT
%     assign variable VAR in caller env. a value from STRUCT.VAR
%   end

%   Henrik Holst
%   Fri, 16 May 2008 21:04:34 +0200

names = fieldnames(struct);
for k = 1:length(names)
	name = names{k};
	assignin('caller',name,getfield(struct,name));
end

It is cool to be able to use this pattern (together with GETOPTS):

% parameters
def.omega = 1.5;
def.plotevery = 0;
def.maxit = 1000;
def.maxerr = 1e-8;
def.plotevery = 0;

opt = getopts(fieldnames(def),varargin{:});
explode(def);
explode(opt);

or in a subroutine like this:

function y = foo(x)
A = 1;
omega = pi;
explode(getopts(who, varargin{:}));
y = A*sin(omega*x);
Personal tools