Using fzero to solve an equation with different constants every time

9 次查看(过去 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

采纳的回答

Jeremy
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 个评论
Catherine Castiblanco
I see, but I still have 2 questions
  1. Why it only shows 76 results
  2. And, is there another function I can use so matlab show me the complex numbers?
Thank you!
Jeremy
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 CenterFile Exchange 中查找有关 Optimization 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by