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