Fsolve iteratively

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
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:

1 Comment

Tim
Tim on 8 Jul 2011
I tried to use the anonmymous function but matlab was not able to retrieve the values from the base workspace. What I need is some help how matlab would iteratively repeat the function. I thought about using a for loop. But I am not sure how this would like with this function.

Sign in to comment.

Friedrich
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

Asked:

Tim
on 8 Jul 2011

Community Treasure Hunt

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

Start Hunting!