]> Creatis software - CreaPhase.git/blob - octave_packages/symbolic-1.1.0/findsym.m
Add a useful package (from Source forge) for octave
[CreaPhase.git] / octave_packages / symbolic-1.1.0 / findsym.m
1 ## Copyright (C) 2003 Willem J. Atsma <watsma@users.sf.net>
2 ##
3 ## This program is free software; you can redistribute it and/or
4 ## modify it under the terms of the GNU General Public
5 ## License as published by the Free Software Foundation;
6 ## either version 2, or (at your option) any later version.
7 ##
8 ## This software is distributed in the hope that it will be useful,
9 ## but WITHOUT ANY WARRANTY; without even the implied
10 ## warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
11 ## PURPOSE.  See the GNU General Public License for more
12 ## details.
13 ##
14 ## You should have received a copy of the GNU General Public
15 ## License along with this software; see the file COPYING.  If not,
16 ## see <http://www.gnu.org/licenses/>.
17
18 ## -*- texinfo -*-
19 ## @deftypefn {Function File} {@var{vars} =} findsym (@var{f}, @var{n})
20 ## Find symbols in expression @var{f} and return them comma-separated in
21 ## string @var{vars}. The symbols are sorted in alphabetic order. If @var{n}
22 ## is specified, the @var{n} symbols closest to "x" are returned.
23 ##
24 ## Example:
25 ## @example
26 ## symbols
27 ## x     = sym ("x");
28 ## y     = sym ("y");
29 ## f     = x^2+3*x*y-y^2;
30 ## vars  = findsym (f);
31 ## vars2 = findsym (f,1);
32 ## @end example
33 ##
34 ## This is intended for m****b compatibility, calls findsymbols().
35 ## @seealso{findsymbols}
36 ## @end deftypefn
37
38 function VARS = findsym(F,Nout)
39
40   symlist = findsymbols(F);
41   Nlist = length(symlist);
42   if Nlist==0
43     warning("No symbols were found.")
44     VARS = "";
45     return
46   endif
47
48   if exist("Nout")!=1
49     VARS = disp(symlist{1});
50     for i=2:Nlist
51       VARS = [VARS "," disp(symlist{i})];
52     endfor
53     return
54   else
55     ## If Nout is specified, sort anew from x.
56     symstrings = disp(symlist{1});
57     for i=2:Nlist
58       symstrings = [symstrings ; disp(symlist{i})];
59     endfor
60
61     symasc = toascii(symstrings);
62
63     if Nlist<Nout
64       warning("Asked for %d, variables, only %d found.",Nout,Nlist);
65       Nout=Nlist;
66     endif
67     symasc(:,1) = abs(toascii("x")-symasc(:,1));
68
69     ## Sort by creating an equivalent number for each entry
70     Nc = length(symasc(1,:));
71     powbase=zeros(Nc,1); powbase(Nc)=1;
72     for i=(Nc-1):-1:1
73       powbase(i) = powbase(i+1)*128;
74     endfor
75     [xs,I]=sort(symasc*powbase);
76
77     VARS = deblank(symstrings(I(1),:));
78
79     for i=2:Nout
80       VARS = [VARS "," deblank(symstrings(I(i),:))];
81     endfor
82
83   endif
84 endfunction
85
86 %!test
87 %! symbols
88 %! x=sym("x"); y=sym("y"); f=x^2+3*x*y-y^2;
89 %! vars = findsym (f);
90 %! assert(vars, 'x,y');
91 %! vars2 = findsym (f,1);
92 %! assert(vars2, 'x');