Code covered by the BSD License  

Highlights from
Optional function arguments

Optional function arguments

by

 

Optional function arguments with default values: optndfts

optndfttest
function optndfttest
% optndfttest  Tests for optndft
%  2012-10-31  Matlab8  Copyright (c) 2012, W J Whiten  BSD License

disp(' ')
disp('No optional values')
testfn(3,4)

disp(' ')
disp('List optional values')
testfn(3,4,'cc',33,'aa',11);

disp(' ')
disp('Optional values in a cell array')
testfn(3,4,{'bb',22,'cc',33});

disp(' ')
disp('Optional values in a struct')
testfn(1,2,struct('bb',22,'aa',11));

% this is an error
try
    disp(' ')
    disp('*** Error case ***')
    testfn(4,5,'zz',99);
catch err
    disp(err.message)
    disp('Error case ok')
end

% also test without varargin in first argument
disp(' ')
disp('Test options for first argument')
cellin=optndfts({'aa',11,'cc',33},'aa',1,'bb',2,'cc',3)
structin=optndfts(struct('aa',11,'cc',33),'aa',1,'bb',2,'cc',3)

return
end



function testfn(a,b,varargin) %#ok<INUSL>

% three ways default values can be specified
listarg=optndfts(varargin,'aa',1,'bb',2,'cc',3)
cellarg=optndfts(varargin,{'aa',1,'bb',2,'cc',3})
structarg=optndfts(varargin,struct('aa',1,'bb',2,'cc',3))

return
end



%  optndftstest
%  
% No optional values
% listarg = 
%     aa: 1
%     bb: 2
%     cc: 3
% cellarg = 
%     aa: 1
%     bb: 2
%     cc: 3
% structarg = 
%     aa: 1
%     bb: 2
%     cc: 3
%  
% List optional values
% listarg = 
%     aa: 11
%     bb: 2
%     cc: 33
% cellarg = 
%     aa: 11
%     bb: 2
%     cc: 33
% structarg = 
%     aa: 11
%     bb: 2
%     cc: 33
%  
% Optional values in a cell array
% listarg = 
%     aa: 1
%     bb: 22
%     cc: 33
% cellarg = 
%     aa: 1
%     bb: 22
%     cc: 33
% structarg = 
%     aa: 1
%     bb: 22
%     cc: 33
%  
% Optional values in a struct
% listarg = 
%     aa: 11
%     bb: 22
%     cc: 3
% cellarg = 
%     aa: 11
%     bb: 22
%     cc: 3
% structarg = 
%     aa: 11
%     bb: 22
%     cc: 3
%  
% *** Error case ***
% Invalid field name  zz
% Error case ok
%  
% Test options for first argument
% cellin = 
%     aa: 11
%     bb: 2
%     cc: 33
% structin = 
%     aa: 11
%     bb: 2
%     cc: 33

Contact us