Using fzero to solve an equation with different constants every time

4 views (last 30 days)
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

Accepted Answer

Jeremy
Jeremy on 22 Nov 2019
Edited: Jeremy on 22 Nov 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 Comments
Catherine Castiblanco
Catherine Castiblanco on 22 Nov 2019
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 on 22 Nov 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

Sign in to comment.

More Answers (0)

Categories

Find more on Optimization 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!