# how to use fzero is for loop?

6 views (last 30 days)
Dameon Solestro on 11 Dec 2021
Answered: Dyuman Joshi on 11 Dec 2021
Im trying to solve quadratic formulas in for-loop where the previous x value is needed for the next loop.
x(1)=10
for i=2:4
f=@(x) (x(i)^2)-(3*x(i)*(x(i-1)))-4
x(i)=fzero(f,0,[])
end
x'
Error using fzero>localFirstFcnEval (line 729)
FZERO cannot continue because user-supplied
function_handle ==> @(x)(x(i)^2)-(3*x(i)*(x(i-1)))-4
failed with the error below.
Index exceeds the number of array elements. Index
must not exceed 1.
Error in fzero (line 286)
fx = localFirstFcnEval(FunFcn,FunFcnIn,x,varargin{:});
Error in randnot (line 3)
x(i)=fzero(f,0,[])
Is there any way to fix this??

Dyuman Joshi on 11 Dec 2021
How exactly will your f be defined if x(i) is not defined. Not sure what you want to do but, Try this -
x(1)=10;
for i=2:4
y=roots([1 -3*x(i-1) -4]);
x(i) = y(abs(y)==min(abs(y)));
end
x'
ans = 4×1
10.0000 -0.1327 1.8108 -0.6569

### Categories

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