将Matlab函数转换为Simulink函数时遇到问题

时间:2020-09-12 10:37:05

标签: matlab model-view-controller simulink predict gradient-descent

我需要转换此函数,该函数实现了梯度下降算法:

function [xopt, fopt, niteration, gnorm, dx] = grad_descent2(varargin)

if nargin == 0
    x0 = [3 3]';
elseif nargin == 1
    x0 = varargin{1};
end

tolerance = 1e-6;
maxiteration = 1000;
dxmin = 1e-6;
alpha = 0.01;
gnorm = inf;
x = x0;
niteration = 0;
dx = inf;

f = @(x1, x2) x1.^2 + 3*x2.^2;
figure(1); clf; fcontour(f, [-5 5 -5 5]); axis equal;hold on
f2 = @(x) f(x(1), x(2));

while and(gnorm >= tolerance, and(niteration <=maxiteration, dx >= dxmin))
      g = grad(x);
      
      gnorm = norm(g);
      
      xnew = x - alpha*g;
      
      plot([x(1) xnew(1)], [x(2) xnew(2)], 'ko-')
      refresh
      
      niteration = niteration + 1;
      dx = norm(xnew - x);
      x = xnew;
end

xopt = x;
fopt = f2(xopt);
niteration = niteration - 1;
end

function g = grad(X)

g = [2*X(1) 
    2*X(2)];

end 

我要最小化的X是pmsm电机模型的值。此刻,我写了这个脚本:

function[x1opt,x2opt]    = grad_descent2(isdpred,isqerr,isdmiss,isqmiss)
x1=isdpred;
x2=isqerr;
x0=[isdmiss,isqmiss];

tolerance = 1e-6;
maxiteration = 1000;
dxmin = 1e-6;
alpha = 0.01;
gnorm = inf;
x = x0;
niteration = 0;
dx = inf;

f = x1.^2+x2.^2;
figure(1); clf; fcontour(f, [-5 5 -5 5]); axis equal;hold on


while and(gnorm >= tolerance, and(niteration <=maxiteration, dx >= dxmin))
      g = grad(x);
      
      gnorm = norm(g);
      
      xnew = x - alpha*g;
      
      niteration = niteration + 1;
      dx = norm(xnew - x);
      x = xnew;
end

x1opt=x(1);
x2opt=x(2);

niteration = niteration - 1;
end

function g = grad(X)

g = [2*X(1)
     2*X(2)];

end

但是Simulink报告此错误:

此功能未完全设置输出端口2的尺寸

0 个答案:

没有答案