Using fzero to solve an equation with different constants every time
3 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Catherine Castiblanco
el 22 de Nov. de 2019
Comentada: Jeremy
el 22 de Nov. de 2019
Hello, I want to solve for x(i) the function F for multiple values of theta and record each x(i). I used the code below to do it but the following error appears:
Error using fzero (line 290)
The function values at the interval endpoints must differ in sign.
Error in main (line 20)
xsol(i)=fzero(@obj_fun,x0);
I do not know why this happens.Any help would be greatly appreciated!
function xsol=main()
r=0.03172;
s=0.333;
rho=0.01;
b=2.5;
tau=0.286;
x0=[0;1];
%values for tau
theta_pool = 0:0.01:0.75;
%Call fsolve in a loop
for i = 1 : numel(theta_pool)
theta = theta_pool(i);
xsol(i)=fzero(@obj_fun,x0);
end
function F = obj_fun(x)
F=(r*((1-tau)*s*(x.^(1-s))*(1-theta))/(r-theta*(1-tau)*s*x.^(1-s)))- rho -(x.^(s)/b)-r+(tau/b);
end
end
%call the result by typing result=main
0 comentarios
Respuesta aceptada
Jeremy
el 22 de Nov. de 2019
Editada: Jeremy
el 22 de Nov. de 2019
x0=[0;1];
By passing a vector into fzero you are telling it that you think the solution is between these values, so it will start using this interval. I ran your code replacing this with x0 = 0; and it would appear that the solution to your equation is complex on every iteration. So, fzero only returns a bunch of NaN results
2 comentarios
Jeremy
el 22 de Nov. de 2019
You need to provide a better initial guess (or range) for fzero to iterate on. For example, I changed x0 to 10, and I get real numbers for the first 14 results, and then back to NaN for the remaining. I plotted the case where theta = 0 to get a better idea of where the function is real and close to zero
Más respuestas (0)
Ver también
Categorías
Más información sobre Optimization en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!