Fsolve iteratively
Show older comments
I would like my fsolve function to calculate x and y several times using different values for a, b, c, d, guess1 and guess2. The changing inputs are saved as column vectors each with the same number of values. X and y values should also be saved in column vectors.
My code is:
function solveeqs1()%main function
Guess1= evalin('base', 'Guess1');
Guess2= evalin('base', 'Guess2');
guess=[Guess1; Guess2];
options=optimset('TolFun',1e-12,'TolX',1e-12,'maxiter',1000,'MaxFunEvals', 2000);
[result, fval, exit, output]=fsolve(@eqns,guess, options);
result
fval
eqns(guess)
exit
output
end
function q=eqns(z) %functions to solve
y=z(2);
x=z(1);
a= evalin('base', 'debt');
b= evalin('base', 'equity');
c= evalin('base', 'rfree');
d= evalin('base', 'std');
q(1)=x*normcdf((log(x/a)+(c +0.5*y^2))/y) - a * exp(-c)*normcdf((log(x/a)+(c +0.5*y^2))/y)-y-b;
q(2)=(x/b)*normcdf((log(x/b)+(c +0.5*y^2))/y)*y-d;
end
Thanks for your help.
Answers (2)
Friedrich
on 8 Jul 2011
1 vote
Hi,
I am not sure if I got it right but I think you are looking for the concept called Anonymous Functions. You can find an example here:
Friedrich
on 8 Jul 2011
I would change it to something like this:
function q=eqns(z,a,b,c,d) %functions to solve
y=z(2);
x=z(1);
q(1)=x*normcdf((log(x/a)+(c +0.5*y^2))/y) - a * exp(-c)*normcdf((log(x/a)+(c +0.5*y^2))/y)-y-b;
q(2)=(x/b)*normcdf((log(x/b)+(c +0.5*y^2))/y)*y-d;
end
function solveeqs1()%main function
options=optimset('TolFun',1e-12,'TolX',1e-12,'maxiter',1000,'MaxFunEvals', 2000);
for i=1:what_ever
Guess1= evalin('base', 'Guess1');
Guess2= evalin('base', 'Guess2');
guess=[Guess1; Guess2];
a= evalin('base', 'debt');
b= evalin('base', 'equity');
c= evalin('base', 'rfree');
d= evalin('base', 'std');
anno_func = @(x)eqns(x,a,b,c,d)
[result, fval, exit, output]=fsolve(@anno_func,guess, options);
%do some other stuff
end
Categories
Find more on Startup and Shutdown in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!