Help with Varargin

조회 수: 5 (최근 30일)
Joseph Hughes
Joseph Hughes 2011년 3월 23일
I have a function called MySolve and i am looking to adapt it to use Varargin.
As far as i am aware Varargin allows defaults for parameters to be set. but can be over-ridden if an input is given. I am having trouble understanding the syntax for using Varargin, here is the function MySolve.m that i have written:
function [x,converged]=MySolve(f,x0,tol,maxit)
%Set Converged intial value to 0 (false)
%Set initial value of x as x0
converged=0;
x=x0;
%run a loop from 1 to maxit
for k=0:maxit
x1=x;
r=f(x);
J=MyJacobian(f,x,1e-6);
x=x-(J\r);
if(max(abs(x-x1)))<tol && max(abs(f(x)))<tol
converged=1;
end
end
I am looking to have defaults for tol and maxit as 1e-10 and 100 respectively.
any help is much appreciated.

채택된 답변

Sarah Wait Zaranek
Sarah Wait Zaranek 2011년 3월 23일
I would suggest the following. This way, the input values are reflected. Hardwire the inputs you definitely want, and use varargin to hold the optional inputs.
function [x,converged]=MySolve(f,x0,varargin)
optargin = size(varargin,2);
if optargin == 0
tol = 1e-10;
maxit = 100;
elseif optargin == 1
tol = varargin{1};
maxit = 100;
else
tol = varargin{1};
maxit = varargin{2};
end
  댓글 수: 2
Joseph Hughes
Joseph Hughes 2011년 3월 23일
works perfectly much appreciated :)
Sarah Wait Zaranek
Sarah Wait Zaranek 2011년 3월 23일
No problem. Once you get the hang of it, varargin is sooo useful.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Jarrod Rivituso
Jarrod Rivituso 2011년 3월 23일
Actually you could use nargin to do this. Essentially, nargin tells you the number of the arguments, and you can use it add some code at the beginning of your function to compensate for missing inputs.
An example:
function twoInputs(x,y)
if nargin == 0
x = 1;
y = 2;
end
if nargin == 1
y = 2;
end
disp(x)
disp(y)

카테고리

Help CenterFile Exchange에서 Gain Scheduling에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by