how to use fzero is for loop?

1 次查看(过去 30 天)
Dameon Solestro
Dameon Solestro 2021-12-11
回答: Dyuman Joshi 2021-12-11
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??

回答(1 个)

Dyuman Joshi
Dyuman Joshi 2021-12-11
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

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by