Azzera filtri
Azzera filtri

How can I create m file with several properties?

3 visualizzazioni (ultimi 30 giorni)
Adam il 3 Lug 2015
Risposto: Adam il 3 Lug 2015
Dear MatLab Community,
I would like to create m file function, with several optional inputs for example when I call this m function in my main code I would like to look like this:
A = myfunction(variable1, variable2, variable3,'Method',2,'Noise','RandomWalk');
A = myfunction(variable1, variable2, variable3,'Noise','White','Method',3);
where the property 'Method' can be 1, 2 or 3 , which assign different calculation ways for the same problem in the m files. The property 'Noise' ,let us say, can be 'white', 'randomwalk' or 'none' in the calculations. I also would like to that the default settings let be
A = myfunction(variable1, variable2, variable3);
which is equivalent the
A = myfunction(variable1, variable2, variable3,'Method',1,'Noise','None');
longer inline code.
How can i begin and implement such requirements in the m file script? Or if you can suggest a link, which deals with this implementation, I would appreciate.

Risposte (3)

Julia il 3 Lug 2015

Guillaume il 3 Lug 2015
The Mathworks way is to use inputParser:
function A = myfunction(var1, var2, var3, varargin)
p = inputParser;
addRequired(p, 'var1');
addRequired(p, 'var2');
addRequired(p, 'var3');
addParameter(p, 'Method', 1); %probably want a validation function as well
addParameter(p, 'Noise', none); %probably want a validation function as well
parse(p, var1, var2, var3, varargin{:});
The downside of this is that every time you call the function you have to parse / validate all inputs. If the function is repeatedly called with the same arguments. it's not efficient. My alternative, if you're familiar enough with classes, is to use function objects:
classdef myfunction
Method = 1; %set defaults here
Noise = 'none';
function this = set.Method(this, value)
%do validation on method input
this.method = value;
function this = set.Noise(this, value)
%do validation on noise input
this.Noise = value;
function A = run(this, var1, var2, var3)
%do the work, using this.Noise and this.Method.
%they're already validated, so no check needed.
You'd use the function object like this:
funobject = myfunction;
%specify non-default attribute
funobject.Noise = 'white'
for iter 1:1000
A =, var2, var3);
%the above is fast since you don't have to validate method and noise on each iteration

Adam il 3 Lug 2015
Thank you very much your help. I am going to study your links and suggestions/solutions. Adam


Scopri di più su Argument Definitions in Help Center e File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by