7345
|
1 ## Copyright (C) 2001, 2003, 2004, 2005, 2006, 2007, 2008 Paul Kienzle |
4679
|
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 |
7016
|
7 ## the Free Software Foundation; either version 3 of the License, or (at |
|
8 ## your option) any later version. |
4679
|
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 |
7016
|
16 ## along with Octave; see the file COPYING. If not, see |
|
17 ## <http://www.gnu.org/licenses/>. |
4679
|
18 |
|
19 ## -*- texinfo -*- |
4906
|
20 ## @deftypefn {Function File} {[@var{s1}, @var{s2}, @dots{}, @var{sN}] =} ind2sub (@var{dims}, @var{ind}) |
4679
|
21 ## Convert a linear index into subscripts. |
6631
|
22 ## |
|
23 ## The following example shows how to convert the linear index @code{8} |
7345
|
24 ## in a 3-by-3 matrix into a subscript. The matrix is linearly indexed |
|
25 ## moving from one column to next, filling up all rows in each column. |
6631
|
26 ## @example |
|
27 ## [r, c] = ind2sub ([3, 3], 8) |
|
28 ## @result{} r = 2 |
|
29 ## c = 3 |
|
30 ## @end example |
5642
|
31 ## @seealso{sub2ind} |
4679
|
32 ## @end deftypefn |
|
33 |
|
34 ## Author: Paul Kienzle <pkienzle@kienzle.powernet.co.uk> |
|
35 ## Adapted-by: jwe |
|
36 |
|
37 function varargout = ind2sub (dims, ind) |
|
38 |
|
39 if (nargin == 2) |
6050
|
40 if (isvector (dims) && all (round (dims) == dims)) |
|
41 if (isnumeric (ind) && all (round (ind) == ind)) |
4679
|
42 ntot = prod (dims); |
6050
|
43 if (all (ind > 0 & ind <= ntot)) |
4679
|
44 nd = length (dims); |
|
45 if (nargout > 0) |
|
46 vlen = nargout; |
|
47 else |
|
48 vlen = 1; |
|
49 endif |
|
50 if (nd > vlen); |
|
51 dims(vlen) = prod (dims(vlen:nd)); |
|
52 dims(vlen+1:nd) = []; |
|
53 endif |
|
54 nd = length (dims); |
|
55 scale = [1; cumprod(dims(:))]; |
|
56 for i = nd:-1:2 |
|
57 k = (ind >= scale(i)); |
|
58 r = ones (size (ind)); |
|
59 t = zeros (size (ind)); |
|
60 t(k) = floor ((ind(k) - 1) / scale(i)); |
|
61 r(k) = t(k) + 1; |
|
62 varargout{i} = r; |
|
63 ind(k) -= t(k) * scale(i); |
|
64 endfor |
|
65 varargout{1} = ind; |
|
66 for i = nd+1:vlen |
|
67 varargout{i} = ones (size (ind)); |
|
68 endfor |
|
69 else |
|
70 error ("ind2sub: index out of range"); |
|
71 endif |
|
72 else |
|
73 error ("ind2sub: expecting integer-valued index argument"); |
|
74 endif |
|
75 else |
5518
|
76 error ("ind2sub: expecting dims to be an integer vector"); |
4679
|
77 endif |
|
78 else |
6046
|
79 print_usage (); |
4679
|
80 endif |
|
81 |
|
82 |
|
83 endfunction |