matlab运行出错,我是18版本的
请问各位,我的代码哪里有问题?
function[x,miny] = minFHXF(y ,g ,X ,alpha ,sita ,gama ,beta ,var ,e)
% y:目标函数
% g:约束函数
% X:初始复合形
% alpha:反复系数
% sita:紧缩系数
% gama:扩展系数
% beta:收缩系数
% var:自变量向量
% e:精度
% x:目标函数取最小值时的自变量
% miny:目标函数的最小值
if nargin==8
e = 1.0e-6;
end
N = size(X);
n = N(2);
FX = zeros(1,n);
while 1
for i = 1:n
FX(i) = subs(y,var,sym(X(:,i)));
end
[XS,IX] = sort(FX);
Xsorted = X(:,IX);
px = sum(Xsorted(:,1:(n-1)),2)/(n-1);
Fpx = subs(y,var,sym(px));
SumF = 0;
for i=1:n
SumF = SumF+(FX(IX(i))-Fpx)^2;
end
SumF = sqrt(SumF/(n-1));
if SumF<=e
x=Xsorted(:,1);
break;
else
bcon_1 = 1;
cof_alpha = alpha;
while bcon_1
x2 = px+cof_alpha*(px-Xsorted(:,n));
gx2 = subs(g,var,sym(x2));
if min(gx2)>=0
bcon_1 = 0;
else
cof_alpha = 0.7*(cof_alpha);
end
end
yx2 = subs(y,var,sym(x2));
if yx2<XS(1)
cof_gama = gama;
bcon_2 = 1;
while bcon_2
x3 = x2+cof_gama*(x2-px);
gx3 = subs(g,var,sym(x3));
yx3 = subs(y,var,sym(x3));
if min(gx3)>=0
bcon_2 = 0;
if yx3<XS(1)
count = 1;
else
count = 2;
end
else
bcon_2 = 0;
count = 3;
end
end
if count==1
Xsorted(:,n) = x3;
X = Xsorted;
continue
else
Xsorted(:,n) = x2;
X = Xsorted;
continue
end
else
if yx2<XS(n-1)
Xsorted(:,n) = x2;
X = Xsorted;
continue
else
if yx2<XS(n)
Xsorted(:,n) = x2;
cof_beta = beta;
bcon_3 =1 ;
while bcon_3<4
x4 = Xsorted(:,n)+cof_beta*(px-Xsorted(:,n));
gx4 = subs(g,var,sym(x4));
if min(gx4)>=0
bcon_3 = 5;
else
cof_beta = cof_beta/2;
bcon_3 = bcon_3+1;
end
end
if min(gx4)>=0
yx4 = subs(y,var,sym(x4));
FNnew = subs(y,var,sym(Xsorted(:,n)));
if yx4Xsorted(:,n)=x4;
X = Xsorted;
continue
else
x0 = Xsorted(:,1);
for i = 1:n
Xsorted(:,i) = x0+sita*(Xsorted(:,i)-x0);
end
end
else
x0 = Xsorted(:,1);
for i = 1:n
Xsorted(:,i) = x0+sita*(Xsorted(:,i)-x0);
X = Xsorted;
continue
end
end
else
x0 = Xsorted(:,1);
for i = 1:n
Xsorted(:,i) = x0+sita*(Xsorted(:,i)-x0);
X = Xsorted;
end
end
end
end
end
X = Xsorted;
end
miny = subs(y,var,sym(x));
这是我的目标函数
syms x1 x2;
y = (x1-3)^2+x2^2;
g = [4-x1^2-x2;x2;x1-0.5];
X = [0.5 1 0.6 0.9;2 2 3 2.6];
[x,miny] = minFHXF(y,g,X,1.3,0.5,1,0.5,[x1 x2])
错误使用 sym/subs>normalize (line 226)
Inconsistency between sizes of second and third arguments.
出错 sym/subs>mupadsubs (line 157)
[X2,Y2,symX,symY] = normalize(X,Y); %#ok
出错 sym/subs (line 145)
G = mupadsubs(F,X,Y);
出错 minFHXF (line 21)
FX(i) = subs(y,var,sym(X(:,i)));
参考GPT和自己的思路:
根据错误提示,可以发现是在 subs 函数中出现了参数不匹配的情况,可能是输入的自变量向量 var 与 sym(X(:,i)) 的大小不一致导致的。建议在运行 subs 函数之前,先检查下 var 的维度是否与 X(:,i) 相等。另外,在使用 subs 函数时,也可以将自变量向量和变量名一起传递过去,避免出现不匹配的情况,如:FX(i) = subs(y,[x1,x2],[X(1,i),X(2,i)]);。