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 Center および File ExchangeOptimization についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by