필터 지우기
필터 지우기

How can I create m file with several properties?

조회 수: 3 (최근 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개)

Julia
Julia 2015년 7월 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

카테고리

Help CenterFile Exchange에서 Argument Definitions에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by