Passing arguments into fsolve without using globals

Hello,
How do I pass arguments, vectors, or constants into fsolve? A simple example:
REF=[x,y,z] <-- I want this to pass into 'myfun' during fsolve
[out,fval]=fsolve('myfun',y0)
...
function [Z]=myfun(y)
Z=[ REF(1)*y(1) + REF(2);
REF(3)*y(2) - REF(2)];
I am trying to avoid using globals.

 採用された回答

Matt Tearle
Matt Tearle 2011 年 10 月 21 日

15 投票

1) Rewrite myfun to take two inputs:
function Z = myfun(y,REF)
...
2) Use an anonymous function handle to make a function of one variable, with the second input to myfun (REF) embedded into it:
REF = [x,y,z];
f = @(y) myfun(y,REF); % function of dummy variable y
[out,fval]=fsolve(f,y0)

4 件のコメント

Jesse
Jesse 2011 年 10 月 26 日
Hooray! Thanks again Matt (you helped me last year).
BTW, using globals, although naughty, is appealing. How do you suggest I pass a file ID (for a debug.txt for example) into my functions. Without globals my functions get really long...
myfun(x,y,time,fid,const1,const2,const3,start,stop,etc,etc)
Matt Tearle
Matt Tearle 2011 年 10 月 26 日
The joy of cells or structures
myfun(x,y,time,lotsostuff)
c5 = lotsostuff.constant5;
f = lotsostuff.filename;
etc
That's essentially how ode45, fminsearch, and the like pass options -- via a structure (that's created using odeset or optimset).
Jesse
Jesse 2011 年 10 月 28 日
Good idea. I am familiar with structures in C-code. I think I should have no prob putting it into MATLAB format.
MADAN MOHAN
MADAN MOHAN 2018 年 6 月 17 日
Hello! I have been trying with reference to your example but i am getting certain errors: So in one script file "eqns.m", I have written the following lines of codes:
function F = eqns(x,k)
x1=x(1);
x2=x(2);
F(1) = x1.^2 + 2*x2.^2 - 5*x1 + 7*x2 - k;
F(2) = 3*x1.^2 - x2.^2 + 4*x1 +2*x2 - k;
end
And the other script file for the calling of the function into the fsolve is:
function f = solveit(x1, x2, k)
x0 = [x1; x2];
[z,fval] = fsolve(@(x)eqns(x,k),x0);
f = z;
end
And I call this function "solveit" in the commend window and I get the following error:
>> solveit(1,2,30)
Error using eqns
Too many input arguments.
Error in solveit>@(x)eqns(x,k) (line 7) [z,fval] = fsolve(@(x)eqns(x,k),x0);
Error in fsolve (line 217) fuser = feval(funfcn{3},x,varargin{:});
Error in solveit (line 7) [z,fval] = fsolve(@(x)eqns(x,k),x0);
Caused by: Failure in initial user-supplied objective function evaluation. FSOLVE cannot continue.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeSimulink Environment Customization についてさらに検索

質問済み:

2011 年 10 月 21 日

コメント済み:

2018 年 6 月 17 日

Community Treasure Hunt

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

Start Hunting!

Translated by