Bababarghi
Bababarghi

Reputation: 581

Matlab - How to generate LaTeX out of a transfer function?

I have a transfer function as:

TF =

0.00995 z^7 - 0.02786 z^6 + 0.03611 z^5 - 0.0293 z^4 + 0.01565 z^3 - 0.005669 z^2 + 0.001274 z - 0.0001554
----------------------------------------------------------------------------------------------------------
     z^8 - 2.4 z^7 + 3.16 z^6 - 2.664 z^5 + 1.585 z^4 - 0.666 z^3 + 0.1975 z^2 - 0.0375 z + 0.003906

when I try:

[num,den] = tfdata(TF);
syms z
clipboard('copy', latex(poly2sym(cell2mat(num),z)/poly2sym(cell2mat(den),z)));

This is what I get which is not quite what I want :

enter image description here

How can I tweak my answer to look like the original transfer function?

Upvotes: 2

Views: 2899

Answers (1)

Ramashalanka
Ramashalanka

Reputation: 8864

Since evalc('TF') is close to LaTeX format just form a string using regexp. First I make TF, trying to mimic the OPs value so that this is a MWE:

numIn=[0.00995  -0.02786 0.03611 -0.0293 0.01565 -0.005669 0.001274 -0.0001554];   
denIn=[1 -2.4 3.16 -2.664 1.585 -0.666 0.1975 -0.0375 0.003906];
TF=tf(numIn,denIn,1,'variable','z'); 

Then I find the numerator and denominator of the fraction by looking for more than 1 consecutive '-' and go back and forward to the newlines. Finally I form a LaTeX string.

fracparts=regexp(evalc('TF'),'([^\n]*)\n[ ]*-[-]+[ ]*\n([^\n]*)','tokens');
TFlatex=['T(z)=\frac{' fracparts{1}{1} '}{' fracparts{1}{2} '}'];

where fracparts{1}{1} is the numerator and fracparts{1}{2} is the denominator. The output is:

T(z)=\frac{  0.00995 z^7 - 0.02786 z^6 + 0.03611 z^5 - 0.0293 z^4 + 0.01565 z^3 - 0.005669 z^2 + 0.001274 z - 0.0001554}{       z^8 - 2.4 z^7 + 3.16 z^6 - 2.664 z^5 + 1.585 z^4 - 0.666 z^3 + 0.1975 z^2 - 0.0375 z + 0.003906}

which compiles in LaTeX with

\documentclass{standalone}
\begin{document}
$T(z)=\frac{  0.00995 z^7 - 0.02786 z^6 + 0.03611 z^5 - 0.0293 z^4 + 0.01565 z^3 - 0.005669 z^2 + 0.001274 z - 0.0001554}{       z^8 - 2.4 z^7 + 3.16 z^6 - 2.664 z^5 + 1.585 z^4 - 0.666 z^3 + 0.1975 z^2 - 0.0375 z + 0.003906}$
\end{document}

to give

enter image description here

For reference, I originally suggested using vpa (http://mathworks.com/help/symbolic/vpa.html) to convert the rationals back into decimals, but this didn't work for the OP, either because we have different Matlab versions, or because my test TF was different.

Upvotes: 1

Related Questions