4679
|
1 ## Copyright (C) 2001 Paul Kienzle <pkienzle@kienzle.powernet.co.uk> |
|
2 ## |
|
3 ## This file is part of Octave. |
|
4 ## |
|
5 ## Octave is free software; you can redistribute it and/or modify it |
|
6 ## under the terms of the GNU General Public License as published by |
|
7 ## the Free Software Foundation; either version 2, or (at your option) |
|
8 ## any later version. |
|
9 ## |
|
10 ## Octave is distributed in the hope that it will be useful, but |
|
11 ## WITHOUT ANY WARRANTY; without even the implied warranty of |
|
12 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |
|
13 ## General Public License for more details. |
|
14 ## |
|
15 ## You should have received a copy of the GNU General Public License |
|
16 ## along with Octave; see the file COPYING. If not, write to the Free |
5307
|
17 ## Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA |
|
18 ## 02110-1301, USA. |
4679
|
19 |
|
20 ## -*- texinfo -*- |
|
21 ## @deftypefn {Function File} {@var{ind} =} sub2ind (@var{dims}, @var{i}, @var{j}) |
|
22 ## @deftypefnx {Function File} {@var{ind} =} sub2ind (@var{dims}, @var{s1}, @var{s2}, @dots{}, @var{sN}) |
|
23 ## Convert subscripts into a linear index. |
|
24 ## @end deftypefn |
5053
|
25 ## |
4679
|
26 ## @seealso{ind2sub} |
|
27 |
|
28 ## Author: Paul Kienzle <pkienzle@kienzle.powernet.co.uk> |
|
29 ## Adapted-by: jwe |
|
30 |
|
31 function ind = sub2ind (dims, varargin) |
|
32 |
|
33 if (nargin > 1) |
|
34 if (isvector (dims) && round (dims) == dims) |
|
35 nd = length (dims); |
|
36 vlen = length (varargin); |
|
37 dims(vlen) = prod (dims(vlen:nd)); |
|
38 dims(vlen+1:nd) = []; |
|
39 scale = cumprod (dims(:)); |
|
40 for i = 1:vlen |
|
41 arg = varargin{i}; |
|
42 if (isnumeric (arg) && round (arg) == arg) |
|
43 if (i == 1) |
|
44 if (arg > 0 & arg <= dims(i)) |
|
45 ind = first_arg = arg; |
|
46 else |
|
47 error ("sub2ind: index out of range"); |
|
48 endif |
|
49 else |
4911
|
50 if (prod (size (first_arg)) == prod (size (arg))) |
4679
|
51 if ((i > nd && arg == 1) || (arg > 0 & arg <= dims(i))) |
4911
|
52 ind(:) += scale(i-1) * (arg(:) - 1); |
4679
|
53 else |
|
54 error ("sub2ind: index out of range"); |
|
55 endif |
|
56 else |
|
57 error ("sub2ind: all index arguments must be the same size"); |
|
58 endif |
|
59 endif |
|
60 else |
|
61 error ("sub2ind: expecting integer-valued index arguments"); |
|
62 endif |
|
63 endfor |
|
64 else |
|
65 error ("sub2ind: expecting dims to be an integer vector"); |
|
66 endif |
|
67 else |
|
68 usage ("sub2ind (dims, i1, i2, ..., iN)"); |
|
69 endif |
|
70 |
|
71 |
|
72 endfunction |