Need help with error in for loop

1 view (last 30 days)
Nick Doherty
Nick Doherty on 2 Dec 2021
Commented: Nick Doherty on 2 Dec 2021
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 Comment
KSSV
KSSV on 2 Dec 2021
Your variables all are scalars and you are trying to access them as vectors.

Sign in to comment.

Answers (1)

Jan
Jan on 2 Dec 2021
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 Comments
Nick Doherty
Nick Doherty on 2 Dec 2021
Nevermind, solved.
For every check in the if statement, make sure it is f1(i) and f2(i)
Thanks

Sign in to comment.

Products


Release

R2019a

Community Treasure Hunt

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

Start Hunting!