0

I need to convert this function, which implements the gradient descent algorithm:

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 

My X to minimize is the value to do of a model of a pmsm motor. At the moment, I write this script:

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

But Simulink reports this error:

This function does not fully set the dimensions of output port 2

Cris Luengo
  • 55,762
  • 10
  • 62
  • 120
  • Simulink is a graphical model system, which may export code. I cant see your [call to the Simulink function name](https://de.mathworks.com/help/simulink/ug/call-simulink-functions-from-matlab-system-block.html), so I am very unsure which parts of the code needs to be moved to [Simulink](https://de.mathworks.com/help/simulink/simulink-functions-in-simulink-models.html). Also please provide a complete example. Your call of the function is missing. – Jay-Pi Sep 12 '20 at 18:56
  • i need to minimize the function f, bacause is composed by the value of two current from an MPC model of a PMSM motor – Dario D'Arpa Sep 13 '20 at 10:50

0 Answers0