]> Creatis software - CreaPhase.git/blob - octave_packages/control-2.3.52/tfpoly2str.m
Add a useful package (from Source forge) for octave
[CreaPhase.git] / octave_packages / control-2.3.52 / tfpoly2str.m
1 ## Copyright (C) 2012   Lukas F. Reichlin
2 ##
3 ## This file is part of LTI Syncope.
4 ##
5 ## LTI Syncope is free software: you can redistribute it and/or modify
6 ## it under the terms of the GNU General Public License as published by
7 ## the Free Software Foundation, either version 3 of the License, or
8 ## (at your option) any later version.
9 ##
10 ## LTI Syncope is distributed in the hope that it will be useful,
11 ## but WITHOUT ANY WARRANTY; without even the implied warranty of
12 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 ## GNU General Public License for more details.
14 ##
15 ## You should have received a copy of the GNU General Public License
16 ## along with LTI Syncope.  If not, see <http://www.gnu.org/licenses/>.
17
18 ## -*- texinfo -*-
19 ## @deftypefn {Function File} {@var{str} =} tfpoly2str (@var{p})
20 ## @deftypefnx {Function File} {@var{str} =} tfpoly2str (@var{p}, @var{tfvar})
21 ## Return the string of a polynomial with string @var{tfvar} as variable.
22 ## @end deftypefn
23
24 ## Author: Lukas Reichlin <lukas.reichlin@gmail.com>
25 ## Created: May 2012
26 ## Version: 0.1
27
28 function str = tfpoly2str (p, tfvar = "x")
29
30   ## TODO: simplify this ugly code
31
32   str = "";
33
34   lp = numel (p);
35
36   if (lp > 0)               # first element (lowest order)
37     idx = find (p);         # first non-zero element
38     if (isempty (idx))
39       str = "0";
40       return;
41     else
42       idx = idx(1);
43     endif
44     a = p(idx);
45
46     if (a < 0)
47       cs = "-";
48     else
49       cs = "";
50     endif
51     
52     if (idx == 1)
53       str = [cs, num2str(abs (a), 4)];
54     else
55       if (abs (a) == 1)
56         str = [cs, __variable__(tfvar, idx-1)];
57       else
58         str = [cs, __coefficient__(a), " ", __variable__(tfvar, idx-1)];
59       endif
60     endif
61
62     if (lp > idx)           # remaining elements of higher order
63       for k = idx+1 : lp
64         a = p(k);
65
66         if (a != 0)
67           if (a < 0)
68             cs = " - ";
69           else
70             cs = " + ";
71           endif
72
73           if (abs (a) == 1)
74             str = [str, cs, __variable__(tfvar, k-1)];
75           else
76             str = [str, cs, __coefficient__(a), " ", __variable__(tfvar, k-1)];
77           endif
78         endif
79       endfor
80
81     endif
82   endif
83
84 endfunction
85
86
87 function str = __coefficient__ (a)
88
89   b = abs (a);  
90
91   if (b == 1)
92     str = "";
93   else
94     str = num2str (b, 4);
95   endif
96
97 endfunction
98
99
100 function str = __variable__ (tfvar, n)
101
102   str = [tfvar, "^-", num2str(n)];
103
104 endfunction