%% Linearization Using MATLAB Code
% This example shows how to obtain a linear model of a plant using a MATLAB script.
% For this example the CSTR model, CSTR_OpenLoop, is linearized. The model inputs are the coolant temperature (manipulated variable of the MPC controller), limiting reactant concentration in the feed stream, and feed temperature. The model states are the temperature and concentration of the limiting reactant in the product stream. Both states are measured and used for feedback control.
%% Obtain Steady-State Operating Point
% The operating point defines the nominal conditions at which you linearize a model. It is usually a steady-state condition.
% Suppose that you plan to operate the CSTR with the output concentration,  C_A, at 2\;kmol/{m^3}. The nominal feed concentration is  10\;kmol/{m^3}, and the nominal feed temperature is 300 K. Create an operating point specification object to define the steady-state conditions.

opspec = operspec('CSTR_OpenLoop');
opspec = addoutputspec(opspec,'CSTR_OpenLoop/CSTR',2);
opspec.Outputs(1).Known = true;
opspec.Outputs(1).y = 2;

op1 = findop('CSTR_OpenLoop',opspec);

% The calculated operating point is C_A = 2\;kmol/{m^3} and T_K = 373 K. Notice that the steady-state coolant temperature is also given as 299 K, which is the nominal value of the manipulated variable of the MPC controller.
% To specify:
% Values of known inputs, use the Input.Known and Input.u fields of opspec
% Initial guesses for state values, use the State.x field of opspec
%
% For example, the following code specifies the coolant temperature as 305 K and initial guess values of the C_A and T_K states before calculating the steady-state operating point:

opspec = operspec('CSTR_OpenLoop');
opspec.States(1).x = 1;
opspec.States(2).x = 400;
opspec.Inputs(1).Known = true;
opspec.Inputs(1).u = 305;

op2 = findop('CSTR_OpenLoop',opspec);

%
%% Specify Linearization Inputs and Outputs
% If the linearization input and output signals are already defined in the model, as in CSTR_OpenLoop, then use the following to obtain the signal set.

io = getlinio('CSTR_OpenLoop');

%
% Otherwise, specify the input and output signals as shown here.

io(1) = linio('CSTR_OpenLoop/Coolant Temperature',1,'input');
io(2) = linio('CSTR_OpenLoop/Feed Concentration',1,'input');
io(3) = linio('CSTR_OpenLoop/Feed Temperature',1,'input');
io(4) = linio('CSTR_OpenLoop/CSTR',1,'output');
io(5) = linio('CSTR_OpenLoop/CSTR',2,'output');

%
%% Linearize Model
% Linearize the model using the specified operating point, op1, and input/output signals, io.

sys = linearize('CSTR_OpenLoop',op1,io)

% Copyright 2012 The MathWorks, Inc.