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. |
5642
|
24 ## @seealso{ind2sub} |
4679
|
25 ## @end deftypefn |
|
26 |
|
27 ## Author: Paul Kienzle <pkienzle@kienzle.powernet.co.uk> |
|
28 ## Adapted-by: jwe |
|
29 |
|
30 function ind = sub2ind (dims, varargin) |
|
31 |
|
32 if (nargin > 1) |
|
33 if (isvector (dims) && round (dims) == dims) |
|
34 nd = length (dims); |
|
35 vlen = length (varargin); |
|
36 dims(vlen) = prod (dims(vlen:nd)); |
|
37 dims(vlen+1:nd) = []; |
|
38 scale = cumprod (dims(:)); |
|
39 for i = 1:vlen |
|
40 arg = varargin{i}; |
|
41 if (isnumeric (arg) && round (arg) == arg) |
|
42 if (i == 1) |
|
43 if (arg > 0 & arg <= dims(i)) |
|
44 ind = first_arg = arg; |
|
45 else |
|
46 error ("sub2ind: index out of range"); |
|
47 endif |
|
48 else |
4911
|
49 if (prod (size (first_arg)) == prod (size (arg))) |
4679
|
50 if ((i > nd && arg == 1) || (arg > 0 & arg <= dims(i))) |
4911
|
51 ind(:) += scale(i-1) * (arg(:) - 1); |
4679
|
52 else |
|
53 error ("sub2ind: index out of range"); |
|
54 endif |
|
55 else |
|
56 error ("sub2ind: all index arguments must be the same size"); |
|
57 endif |
|
58 endif |
|
59 else |
|
60 error ("sub2ind: expecting integer-valued index arguments"); |
|
61 endif |
|
62 endfor |
|
63 else |
|
64 error ("sub2ind: expecting dims to be an integer vector"); |
|
65 endif |
|
66 else |
|
67 usage ("sub2ind (dims, i1, i2, ..., iN)"); |
|
68 endif |
|
69 |
|
70 |
|
71 endfunction |