|
Hello everyone.
I'm writing my first S-function (1 level) but I get unexpected results.
Trying to understand what I'm doing wrong I came up with this two pieces of
code which SHOULD do the same thing but they actually don't.
I really don't understand why: can anyone please help?
Basically what I'm trying to implement is a linear system:
x' = A*x + B*u
y = x
The first function uses matrix and outputs the same result as a "state-space
model" simulink block. The second function uses equations (which should
work as well, shouldn't they?) but the output is completely different.
Thank you!
********** S-FUNCTION #1 **********
function [sys,x0,str,ts] = csfunc(t,x,u,flag,angInit)
M = 0.2;
m = 0.3;
l = 0.1;
g = 9.81;
A=[0 1 0 0; 0 0 -m*g/M 0; 0 0 0 1; 0 0 (M+m)*g/(M*l) 0];
B=[0; 1/M ;0 ; -1/(M*l)];
%
% Dispatch the flag.
%
switch flag,
case 0
[sys,x0,str,ts]=mdlInitializeSizes(A,B,angInit); % Initialization
case 1
sys = mdlDerivatives(t,x,u,A,B); % Calculate derivatives
case 3
sys = mdlOutputs(t,x,u,A,B); % Calculate outputs
case { 2, 4, 9 } % Unused flags
sys = [];
otherwise
error(['Unhandled flag = ',num2str(flag)]); % Error handling
end
function [sys,x0,str,ts] = mdlInitializeSizes(A,B,angInit)
sizes = simsizes;
sizes.NumContStates = 4;
sizes.NumDiscStates = 0;
sizes.NumOutputs = 4;
sizes.NumInputs = 1;
sizes.DirFeedthrough = 0;
sizes.NumSampleTimes = 1;
sys = simsizes(sizes);
x0 = [0;0;angInit;0];
str = [];
ts = [0 0];
function sys = mdlDerivatives(t,x,u,A,B)
sys = A*x + B*u;
function sys = mdlOutputs(t,x,u,A,B)
sys = x;
********** S-FUNCTION #2 **********
function [sys,x0,str,ts] = sist_non_lin_1_lev(t,x,u,flag,angInit)
switch flag
case 0 % initialize
[sys,x0,str,ts] = mdlInitializeSizes(angInit);
case 1 % derivatives
sys = mdlDerivatives(t,x,u);
case 3 % output
sys = mdlOutputs(t,x,u);
case {2 4 9}
% 2:discrete 4:calcTimeHit 9:termination
sys =[];
otherwise
error(['Error - unhandled flag =',num2str(flag)]) ;
end
function [sys,x0,str,ts] = mdlInitializeSizes(angInit)
sizes = simsizes;
sizes.NumContStates = 4;
sizes.NumDiscStates = 0;
sizes.NumOutputs = 4;
sizes.NumInputs = 1;
sizes.DirFeedthrough = 0;
sizes.NumSampleTimes = 1;
sys = simsizes(sizes);
x0 = [0;0;angInit;0];
str = [];
ts = [0 0];
function sys = mdlDerivatives(t,x,u)
% Variabili
M = 0.2;
m = 0.3;
l = 0.1;
g = 9.81;
x1 = x(1); %posizione
x2 = x(2); %velocita
x3 = x(3); %angolo
x4 = x(4); %vel angolare
F_in = u;
dx1 = x2;
dx2 = ( -m*g*(x3) + F_in ) / M;
dx3 = x4;
dx4 = ( (M+m)*g*(x3) - F_in ) / l*M;
sys = [dx1;dx2;dx3;dx4];
% End of mdlDerivatives.
function sys = mdlOutputs(t,x,u)
sys = x;
% End of mdlOutputs.
|