function defstruct(name,fields,values) % DEFSTRUCT(name,fields,values) % % Assigns default values to the named structure % % INPUT: % % name A string, enclosed in single quotes, with a structure name % fields A cell array with fields that you want the structure to have % values A cell array with the values by which you populate those fields % % OUTPUT: % % None. The variables appear as if by magic into your workspace or % will be available inside your function. % % SEE ALSO: % % CELLNAN, STRUCTNAN, STRUCT % % Last modified by fjsimons-at-alum.mit.edu, 03/16/2012 if ~ischar(name), error(sprintf(['The first argument of DEFSTRUCT',... 'has to be a string with a structure name'])); end % Always do it is our default here si=1; % If it exists... if evalin('caller',[ 'exist(''' name ''',''var'')']); % ... and it's empty, do it; but don't do it if it's non empty si=evalin('caller',[ 'isempty(' name ')']); end % Do it or not if si % Maybe it's only a single field name and value pair if isstr(fields); fields={fields}; end if ~iscell(values); values={values}; end % Do it exactly like OPTIMSET structinput=cell(2,length(fields)); % Fields go in first row structinput(1,:)=fields'; % []'s go in second row structinput(2,:)=values'; % Turn it into correctly ordered comma separated list and call struct S=struct(structinput{:}); % Put in the caller workspace assignin('caller',name,S); end