how to use fzero is for loop?

1 visualización (últimos 30 días)
Dameon Solestro
Dameon Solestro el 11 de Dic. de 2021
Respondida: Dyuman Joshi el 11 de Dic. de 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??

Respuestas (1)

Dyuman Joshi
Dyuman Joshi el 11 de Dic. de 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

Categorías

Más información sobre Optimization en Help Center y File Exchange.

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by