Need help with error in for loop

1 次查看(过去 30 天)
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 CenterFile Exchange 中查找有关 Programming 的更多信息

产品


版本

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by