I write a code about an optimization problem and i face to this error can anybody help me?

2 次查看(过去 30 天)
clc
clear
close all
epsilon=0.01;
er=inf;
syms x1 x2 f_sym(x1,x2);
f_sym(x1,x2)=3+(x1-1.5*x2)^2+(x2-2)^2
f=matlabFunction(f_sym);
grad=matlabFunction(gradient(f_sym));
range=[0 5 0 5];
Ngrid=100;
dx=(range(2)-range(1))/Ngrid;
dy=(range(4)-range(3))/Ngrid;
xgrid=range(1):dx:range(2);
ygrid=range(3):dy:range(4);
[x_1,y_1]=meshgrid(xgrid,ygrid);
for i=1:size(x_1,1)
for j=1:size(x_1,2)
z(i,j)=f(x_1(i,j),y_1(i,j))
end
end
figure(1)
contour(x_1,y_1,z,[3.1 3.25 3.5 4 6 10 15 20 25]);
xlabel('x_1');
ylabel('x_2');
title('steepest descent');
k=0;
syms alpha0 X1(alpha0) X2(alpha0)
while er>epsilon
k=k+1;
if k==1
x0=[0.5 0.5];
x{1}=x0;
display(['iteration1,x(1)=' num2str(x{k}(1)),'x(2)='...
num2str(x{k}(2)),'bestcsot=' num2str(f(x{k}(1),x{k}(2)))]);
pause(1)
f_value(k)=f(x{k}(1),x{k}(2));
hold on;plot(x{k}(1),x{k}(2),'--mo','MarkerEdgeColor',...
'r','MarkerFaceColor','r','MarkerSize',4);
------------------------------------------------------------------------------------------------------------------------------------------- g0=grad(x{k-1}(1),x{k-1}(2));
when i run the program at line 42 i face to this error
Subscript indices must either be real positive integers or logicals.
Error in code (line 42)
g0=grad(x{k-1}(1),x{k-1}(2));
X1(alpha0)=x{k-1}(1)-alpha(0)*g0(1);
X2(alpha0)=x{k-1}(2)-alpha(0)*g0(2);
F(alpha0)=f_sym(x1,x2);
F_diff=diff(F(alpha0),alpha0);
x{k}=x{k-1}-alpha(0)*g0;
f_value=f(x{k}(1),x{k}(2));
er=norm(x{k},x{k-1});
display(['iteration' num2str(k),'x(1)=', num2str(x{k}(1))...
,'x(2)=', num2str(x{k}(2)) ',er=' num2str(er) ...
,'best cost=' num2str(f(x{k}(1),x{k}(2)))]);
pause(1)
hold on; plot(x{k}(1),x{k}(2),'--mo','MarkerEdgeColor','r',...
'MarkerFaceColor','r','MarkerSize',4);
end
end
figure(2)
plot(f_value);
xlabel('number of itration');
ylebel('f(x)');
title('steepest descent');

回答(0 个)

Community Treasure Hunt

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

Start Hunting!

Translated by