Code covered by the BSD License

# Speeding Up Optimization Problems with Parallel Computing

### Stuart Kozola (view profile)

Files from the webinar: Speeding up optimization problems with parallel computing

### Editor's Notes:

This file was selected as MATLAB Central Pick of the Week

motorController(p,u,v)
```function varargout = motorController(p,u,v)
% Controller design function.

% Copyright 2010 The MathWorks, Inc.
%% PID Parameters, P
Kp = p(1);              % proportional gain
Ki = p(2);              % integral gain
Kd = p(3);              % derivative gain

%% U parameters
Kf = u(1);              % friction coefficient
NL = u(2)*2*pi;         % speed request

%% V parameters
La = v(1);              % armature inductance (H)
Ra = v(2);              % armature resistance (Ohms)
Km = v(3);              % motor torque constant
Ja = v(4);              % armature moment of inertia (kg m^2)

Kb = Km;                % back emf constant

%% DC Motor State-Space Model
A = [-Ra/La -Kb/La; Km/Ja -Kf/Ja];
B = [1/La; 0];
C = [0 1];
D = 0;
dc_motor = ss(A,B,C,D,'inputname','voltage','outputname','y','statename',...
{'I','n'});

%% PID Transfer Function
numc= [Kd, Kp, Ki];
numc= [0,0,0.2];
denc=[1 0];
pid = tf(numc,denc,'inputname','e','outputname','voltage');

%% Closed-Loop System
s   = sumblk('e','r','y','+-');
sys = connect(dc_motor,pid,s,'r','y');

%% Simulate System
warning('off','Control:analysis:LsimUndersampled');
[~,t] = step(sys);
r = NL*ones(size(t));
[y,t,x] = lsim(sys, r, t);
voltage = filter(numc,denc,r-y);
error   = r-y;

if isempty(x)
x = zeros(length(t),2);
end

%% Outputs
n   = max(y)/2/pi;                      % rotational speed (rev/s)
V   = max(voltage);                     % design voltage (V)
Pmin= max(voltage.*x(:,1)*1e-3);        % minimum required power (kW)
Tmin= max(Km*x(:,1))*1e-3;              % minimum required torque (kNm)

%% Perfromance Index, J
J = trapz(t,error.^2)/100 + V;

%% Define Use (Objective or Constraint)
c = [];
ceq = [];
switch nargout
case 0 % plot
subplot(2,2,1)
plot(t,y/2/pi,t,r/2/pi,'r'); ylabel('Rotational Speed (rev/s)')
subplot(2,2,2)
plot(t,voltage); ylabel('Voltage (v)');
subplot(2,2,3)
plot(t,voltage.*x(:,1)); ylabel('Power (kW)'); xlabel('Time (s)');
subplot(2,2,4)
plot(t,Km*x(:,1)); ylabel('Torque (Nm)'); xlabel('Time (s)');
case 1 % objective function
varargout{1} = J; % performance index
case 2 % constraints
varargout{1} = c;
varargout{2} = ceq;
case {3,4} % objective, constraints, and control outputs
varargout{1} = J;
varargout{2} = c;
varargout{3} = ceq;
varargout{4} = [n V Pmin Tmin];
end```