by
271 14
0
5
4,204
4
Top 1% !
Popular
Famous
Tagged
Specified
Popularity: 2505th place
Created
Modified Sep 6, 2013
This snippet is Public
LanguageMatlab
LicenseMIT_X11
Resources LanguageM-files

Options in Matlab functions as optional Key-Value pairs

How to add to a custom matlab function the possibility to receive options as key-value pairs
Copy Embed Code
<iframe id="embedFrame" style="width:600px; height:300px;"
src="https://www.snip2code.com/Embed/11170/Options-in-Matlab-functions-as-optional-?startLine=0"></iframe>
Click on the embed code to copy it into your clipboard Width Height
Leave empty to retrieve all the content Start End
function example(varargin) %# define defaults at the beginning of the code so that you do not need to %# scroll way down in case you want to change something or if the help is %# incomplete options = struct('firstparameter',1,'secondparameter',magic(3)); %# read the acceptable names optionNames = fieldnames(options); %# count arguments nArgs = length(varargin); if round(nArgs/2)~=nArgs/2 error('EXAMPLE needs propertyName/propertyValue pairs') end for pair = reshape(varargin,2,[]) %# pair is {propName;propValue} inpName = lower(pair{1}); %# make case insensitive if any(strcmp(inpName,optionNames)) %# overwrite options. If you want you can test for the right class here %# Also, if you find out that there is an option you keep getting wrong, %# you can use "if strcmp(inpName,'problemOption'),testMore,end"-statements options.(inpName) = pair{2}; else error('%s is not a recognized parameter name',inpName) end end
If you want to be updated about similar snippets, Sign in and follow our Channels

blog comments powered by Disqus