function [A,B,C,D] = my_tf2ss(num0, den0)
% Convert transfer function n(s)/d(s) to state space dx/dt=Ax+Bu, y=Cx+Du
% when degree(n(s)) < degree(d(s))
% Feb13 JG

if nargin<1, my_tf2ss_demo; return; end

num= num0(:)'/den0(1); den= den0(:)'/den0(1); % enforce den(1)==1
nn= length(num);
nd= length(den);

if nn>=nd
    % note: nn==nd is also easy (put it here; give error only if nn>nd)
    error('not implemented length(num)>=length(den)');
else
    A= [zeros(nd-2,1) eye(nd-2); -den(end:-1:2)];
    B= [zeros(nd-2,1); 1];
    C= [num(end:-1:1) zeros(1,nd-1-nn)];
    D= 0;
end

return; % end of main function


function my_tf2ss_demo
% Demo: obtain one state space model
%   from the transfer function G(s)=(2s+6)/(s^2+3s+2)

num= [2 6];
den= [1 3 2];
[A,B,C,D] = my_tf2ss(num, den)
