How can I pass additional parameters to a function I defined?

조회 수: 6 (최근 30일)
Hello,
When using an odexx solver I know i can pass additional parameters following this structure (example for ode45)
[T,X] = ode45(f,tspan,x0,[],u,d,par)
where u,d and par are the additional parameters I am passing to ode45.
Is there any way to do the same for a function I defined? As an example, I have the following function
[t,x] = FoxRabbit_Euler_v1(f1,tspan,x0,n);
In this case f1 has some parameters I will like to pass when using "FoxRabbit_Euler_v1".
Any help will be very much appreciated

채택된 답변

Ryan Livingston
Ryan Livingston 2013년 3월 7일
You may want to have a look at varargin:
Defining a function like
function out = foo(a,b,varargin)
...
allows you to require a and b as arguments then allows the user to pass along anything else. These other arguments are put into the cell array varargin and can be retrieved from there:
if (nargin >= 3)
extraInput1 = varargin{1};
elseif (nargin >= 4)
extraInput2 = varargin{2};
...
end
  댓글 수: 4
mauricio
mauricio 2013년 3월 8일
I think I have found the way to use varargin for my particular purpose but there is still a small issue.
I have written the following code just to understand a little better the use of varargin
function s = h(x,varargin)
y=[varargin{:}]
h=y(1)-y(2)
x
end
Here I turn the cell array into a vector and then I use the components of that vector to do something else (a difference in this case). I have play with some scalars and everything is good.
Now I have a new issue. Some of this additional parameters are scalars, others are vectors. i.e (2,[1 3],5). How can I assign each component of the array varargin into a specific variable/parameter inside my code? i.e
u=2
t=[2 3]
par=4
Any hint? Thanks for your time
mauricio
mauricio 2013년 3월 8일
I tried the following function
function s = add(x,varargin)
a = [varargin{1}]
b = [varargin{2}]
c = [varargin{3}]
x
end
and when called add(1,[3 4],6,7) I get the needed result
a = 3 4
b = 6
c = 7
x = 1
Now I can use a,b,c (the additional parameters) inside my original function ;) I do not know if this is the correct way to do it or the most efficient way to use the extra parameters passed to a function, so any comment or suggestion will be very welcome.

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

추가 답변 (1개)

Shashank Prasanna
Shashank Prasanna 2013년 3월 7일
You can use anonymous functions to achieve just that:
Although the above link is from the optimization toolbox the concept is the same and is a pretty standard way across matlab toolboxes to pass additional parameters.
The following should be helpful too:
  댓글 수: 1
mauricio
mauricio 2013년 3월 7일
Thanks Shashank ! In particular the Parameterizing Functions info will help me in the near future ;)

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

카테고리

Help CenterFile Exchange에서 Creating, Deleting, and Querying Graphics Objects에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by