Need help with error in for loop

1 visualizzazione (ultimi 30 giorni)
Nick Doherty
Nick Doherty il 2 Dic 2021
Commentato: Nick Doherty il 2 Dic 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 Commento
KSSV
KSSV il 2 Dic 2021
Your variables all are scalars and you are trying to access them as vectors.

Accedi per commentare.

Risposte (1)

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

Accedi per commentare.

Categorie

Scopri di più su Creating and Concatenating Matrices in Help Center e File Exchange

Prodotti


Release

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by