My coding error during run. Please check my matlab coding. What is the cause?
1 次查看(过去 30 天)
显示 更早的评论
clc
close all
clear all
syms gamma beta e real
syms x1 x2 real
f(x1,x2) = (x1^2 + x2 -11)^2 + (x1 + x2^2 -7)^2; % Function
%% Step 1
% Assume any three sets of solution. Let's say (0,0), (2,0), (1,1);
x = zeros(2,3);
% Input initial simplex points
x(:,1) = [0,0]';
x(:,2) = [2,0]';
x(:,3) = [1,1]';
%Parameters - Change the parameter as per the question
gamma = 1.5;
beta = 0.5;
e_s = 0.001;
e = 1;
iteration = 0;
%% Step 2
while e > e_s
f1 = double(subs(f,[x1,x2],x(:,1)'));
f2 = double(subs(f,[x1,x2],x(:,2)'));
f3 = double(subs(f,[x1,x2],x(:,3)'));
if f1 > f2 && f1 > f3
f_xh = f1;
x_h = x(:,1);
i = 1;
if f2 > f3
f_xl = f3;
f_xg = f2;
x_l = x(:,2);
x_g = x(:,3);
else
f_xl = f2;
f_xg = f3;
x_l = x(:,3);
x_g = x(:,2);
end
x_c = (x_l+ x_g)./2;
elseif f2 > f1 && f2 > f3
f_xh = f2;
x_h = x(:,2);
i = 2;
if f1 > f3
f_xl = f3;
f_xg = f1;
x_l = x(:,3);
x_g = x(:,1);
else
f_xl = f1;
f_xg = f3;
x_l = x(:,1);
x_g = x(:,3);
end
x_c = (x_l + x_g)./2;
else
f_xh = f3;
x_h = x(:,3);
i = 3;
if f1 > f2
f_xl = f2;
f_xg = f1;
x_l = x(:,2);
x_g = x(:,1);
else
f_xl = f1;
f_xg = f2;
x_l = x(:,1);
x_g = x(:,2);
end
x_c = (x_l + x_g)./2;
end
%% Step 3
x_r = 2*x_c - x_h; %Reflected point
f_xr = subs(f,[x1,x2],x_r');
if f_xr < f_xl
x_new = (1+gamma)*x_l - gamma*x_h;
elseif f_xr >= f_xh
x_new = (1-beta)*x_c + beta*x_h;
else
x_new = (1+beta)*x_c - beta*x_h;
end
%% Step 4
f_new = double(subs(f,[x1,x2],x_new'));
f_xc = double(subs(f,[x1,x2],x_c'));
f_final = [f_new, f_xg, f_xl];
e = (sum(((f_final - f_xc).^(2))/3))^(1/2);
x(:,i) = x_new;
iteration = iteration + 1;
end
%% Final result
x_h_final = x_h
x_g_final = x_g
x_l_final = x_l
回答(1 个)
Luca Ferro
2023-1-9
i tried to run the code and i think the error you are referring to is:
> Error using syms: Unable to create a symbolic variable 'gamma' by using 'syms' inside a MATLAB function because 'gamma' is an existing function name, class name, method name, and so on.
if it is like so, try to substitute the syms delcaration;
syms gamma beta e
with
sym('gamma')
sym ('beta')
sym('e')
You will need to change the beta and e declaration as well because they too are existing function names.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Special Functions 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!