How can I create m file with several properties?

8 ビュー (過去 30 日間)
Adam
Adam 2015 年 7 月 3 日
回答済み: Adam 2015 年 7 月 3 日
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');
or
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.
Adam

回答 (3 件)


Guillaume
Guillaume 2015 年 7 月 3 日
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{:});
%...
end
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
properties
Method = 1; %set defaults here
Noise = 'none';
end
methods
function this = set.Method(this, value)
%do validation on method input
this.method = value;
end
function this = set.Noise(this, value)
%do validation on noise input
this.Noise = value;
end
function A = run(this, var1, var2, var3)
%do the work, using this.Noise and this.Method.
%they're already validated, so no check needed.
end
end
You'd use the function object like this:
funobject = myfunction;
%specify non-default attribute
funobject.Noise = 'white'
for iter 1:1000
A = funobject.run(var1, var2, var3);
%the above is fast since you don't have to validate method and noise on each iteration
end

Adam
Adam 2015 年 7 月 3 日
Thank you very much your help. I am going to study your links and suggestions/solutions. Adam

Community Treasure Hunt

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

Start Hunting!

Translated by