]> Creatis software - CreaPhase.git/blob - octave_packages/specfun-1.1.0/multinom.m
Add a useful package (from Source forge) for octave
[CreaPhase.git] / octave_packages / specfun-1.1.0 / multinom.m
1 %% Copyright (c) 2011 Juan Pablo Carbajal <carbajal@ifi.uzh.ch>
2 %%
3 %%    This program is free software: you can redistribute it and/or modify
4 %%    it under the terms of the GNU General Public License as published by
5 %%    the Free Software Foundation, either version 3 of the License, or
6 %%    any later version.
7 %%
8 %%    This program is distributed in the hope that it will be useful,
9 %%    but WITHOUT ANY WARRANTY; without even the implied warranty of
10 %%    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11 %%    GNU General Public License for more details.
12 %%
13 %%    You should have received a copy of the GNU General Public License
14 %%    along with this program. If not, see <http://www.gnu.org/licenses/>.
15
16 %% -*- texinfo -*-
17 %% @deftypefn {Function File} {[@var{y} @var{alpha}] =} multinom (@var{x}, @var{n})
18 %% @deftypefnx {Function File} {[@var{y} @var{alpha}] =} multinom (@var{x}, @var{n},@var{sort})
19 %%
20 %% Returns the terms (monomials) of the multinomial expansion of degree n.
21 %% @tex
22 %% $$
23 %% (x_1 + x_2 + ... + x_m)^N
24 %% $$
25 %% @end tex
26 %% @ifnottex
27 %%
28 %% @example
29 %% (x1 + x2 + ... + xm)^@var{n}
30 %% @end example
31 %%
32 %% @end ifnottex
33 %%
34 %% @var{x} is a nT-by-m matrix where each column represents a different variable, the
35 %% output @var{y} has the same format.
36 %% The order of the terms is inherited from multinom_exp and can be controlled
37 %% through the optional argument @var{sort} and is passed to the function @code{sort}.
38 %% The exponents are returned in @var{alpha}.
39 %%
40 %% @seealso{multinom_exp, multinom_coeff, sort}
41 %% @end deftypefn
42
43 function [y, alpha] = multinom(x,n,sortmethod)
44
45     [nT, m]  = size(x);
46     if nargin > 2
47         alpha = multinom_exp(m,n,sortmethod);
48     else
49         alpha = multinom_exp(m,n);
50     end
51     na      = size(alpha,1);
52
53     y = prod(repmat(x,na,1).^kron(alpha,ones(nT,1)),2);
54     y = reshape(y,nT,na);
55
56 end
57
58 %!demo
59 %! n = 3;
60 %! t = linspace(-1,1,10).';
61 %! x = [t-1/2, t];
62 %! y = multinom(x,n,'descend');
63 %! y_shouldbe = [x(:,1).^3 x(:,2).^3 x(:,1).^2.*x(:,2) x(:,1).*x(:,2).^2 ];
64 %! plot(t,y_shouldbe); hold on; plot(t,y,'s'); hold off;
65 %! legend('x_1^3','x_2^3','x_1^2x_2','x_1x_2^2','location','southoutside',...
66 %! 'orientation','horizontal');
67 %! title('Terms of the expansion of (x_1 + x_2)^3 (colors should match)');