Need help with error in for loop

2 ビュー (過去 30 日間)
Nick Doherty
Nick Doherty 2021 年 12 月 2 日
コメント済み: Nick Doherty 2021 年 12 月 2 日
Using Gold-Section search method to determine max value of f(x)
want to iterate 20 time and each time making the braket smaller to find value
clc
clear
r=((sqrt(5)-1)/2);
d=r*(6)
xL(1)=-2;
xu(1)=4;
x1(1)=xL+d;
x2(1)=xu-d;
f1= zeros(1,20);
f2= zeros(1,20);
for i=1:20
f1(i)=4*x1(i)-1.8*(x1(i)^2)+1.2*(x1(i)^3)-0.3*(x1(i)^4)
f2(i)=4*x2(i)-1.8*(x2(i)^2)+1.2*(x2(i)^3)-0.3*(x2(i)^4)
d(i)=r*(xu(i)-xL(i));
if f1>f2;
xL(i+1)=x2(i);
xu(i+1)=xu(i);
x1(i+1)=x2(i)+d(i)
x2(i+1)=x1(i)
elseif f2>f1;
xL(i+1)=xL(i);
xu(i+1)=x1(i);
x1(i+1)=x2(i)
x2(i+1)=x1(i)-d(i)
end
end
Get error:
Index exceeds the number of array elements (1).
Error in Doherty_Nicholas_BIME450_Hw12 (line 14)
f1(i)=4*x1(i)-1.8*(x1(i)^2)+1.2*(x1(i)^3)-0.3*(x1(i)^4)
  1 件のコメント
KSSV
KSSV 2021 年 12 月 2 日
Your variables all are scalars and you are trying to access them as vectors.

サインインしてコメントする。

回答 (1 件)

Jan
Jan 2021 年 12 月 2 日
Your code tests f1<f2 and f1>f2, but not f1 == f2. In this case x1(i+1) and x2(i+2) are not created.
r = (sqrt(5)-1) / 2;
d = r * 6;
xL(1)=-2;
xu(1)=4;
x1(1)=xL+d;
x2(1)=xu-d;
f1= zeros(1,20);
f2= zeros(1,20);
for i = 1:20
f1(i) = 4 * x1(i) - 1.8 * (x1(i)^2) + 1.2 * (x1(i)^3) - 0.3 * (x1(i)^4);
f2(i) = 4 * x2(i) - 1.8 * (x2(i)^2) + 1.2 * (x2(i)^3) - 0.3 * (x2(i)^4);
d(i) = r * (xu(i) - xL(i));
if f1 > f2
xL(i+1) = x2(i);
xu(i+1) = xu(i);
x1(i+1) = x2(i) + d(i);
x2(i+1) = x1(i);
elseif f2>f1
xL(i+1) = xL(i);
xu(i+1) = x1(i);
x1(i+1) = x2(i);
x2(i+1) = x1(i) - d(i);
else % f1 == f2: What should happen then?!
xL(i+1) = xL(i);
xu(i+1) = xu(i);
x1(i+1) = x1(i);
x2(i+1) = x2(i);
end
end
  2 件のコメント
Nick Doherty
Nick Doherty 2021 年 12 月 2 日
Thank you that helps a little bit
I am still getting the error where my arrays are not changing value are i increases. For example, my f1 and f2 are calculated once and stay constant for the 1x20double
clc
clear
r=((sqrt(5)-1)/2);
f1= zeros(1,20);
f2= zeros(1,20);
for i=1:20
d(1)=r*(6)
xL(1)=-2;
xu(1)=4;
x1(1)=xL(1)+d(1);
x2(1)=xu(1)-d(1);
f1(i)=4*x1(i)-1.8*(x1(i)^2)+1.2*(x1(i)^3)-0.3*(x1(i)^4)
f2(i)=4*x2(i)-1.8*(x2(i)^2)+1.2*(x2(i)^3)-0.3*(x2(i)^4)
d(i)=r.*(xu(i)-xL(i));
if f1>f2;
xL(i+1)=x2(i);
xu(i+1)=xu(i);
x1(i+1)=x2(i)+d(i);
x2(i+1)=x1(i);
elseif f2>f1;
xL(i+1)=xL(i);
xu(i+1)=x1(i);
x1(i+1)=x2(i);
x2(i+1)=x1(i)-d(i);
else f1==f2
xL(i+1) = xL(i);
xu(i+1) = xu(i);
x1(i+1) = x1(i);
x2(i+1) = x2(i);
end
end
Nick Doherty
Nick Doherty 2021 年 12 月 2 日
Nevermind, solved.
For every check in the if statement, make sure it is f1(i) and f2(i)
Thanks

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeProgramming についてさらに検索

製品


リリース

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by