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

问题描述

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

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,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的尺寸

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...