Using fzero to solve an equation with different constants every time
3 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Jeremy
2019-11-22
编辑:Jeremy
2019-11-22
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 个评论
Jeremy
2019-11-22
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
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!