Need help with error in for loop

5 visualizaciones (últimos 30 días)
Nick Doherty
Nick Doherty el 2 de Dic. de 2021
Comentada: Nick Doherty el 2 de Dic. de 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 comentario
KSSV
KSSV el 2 de Dic. de 2021
Your variables all are scalars and you are trying to access them as vectors.

Iniciar sesión para comentar.

Respuestas (1)

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

Iniciar sesión para comentar.

Categorías

Más información sobre Programming en Help Center y File Exchange.

Etiquetas

Productos


Versión

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by