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 -*- |
4906
|
21 ## @deftypefn {Function File} {[@var{s1}, @var{s2}, @dots{}, @var{sN}] =} ind2sub (@var{dims}, @var{ind}) |
4679
|
22 ## Convert a linear index into subscripts. |
6631
|
23 ## |
|
24 ## The following example shows how to convert the linear index @code{8} |
|
25 ## in a 3-by-3 matrix into a subscript. |
|
26 ## |
|
27 ## @example |
|
28 ## [r, c] = ind2sub ([3, 3], 8) |
|
29 ## @result{} r = 2 |
|
30 ## c = 3 |
|
31 ## @end example |
5642
|
32 ## @seealso{sub2ind} |
4679
|
33 ## @end deftypefn |
|
34 |
|
35 ## Author: Paul Kienzle <pkienzle@kienzle.powernet.co.uk> |
|
36 ## Adapted-by: jwe |
|
37 |
|
38 function varargout = ind2sub (dims, ind) |
|
39 |
|
40 if (nargin == 2) |
6050
|
41 if (isvector (dims) && all (round (dims) == dims)) |
|
42 if (isnumeric (ind) && all (round (ind) == ind)) |
4679
|
43 ntot = prod (dims); |
6050
|
44 if (all (ind > 0 & ind <= ntot)) |
4679
|
45 nd = length (dims); |
|
46 if (nargout > 0) |
|
47 vlen = nargout; |
|
48 else |
|
49 vlen = 1; |
|
50 endif |
|
51 if (nd > vlen); |
|
52 dims(vlen) = prod (dims(vlen:nd)); |
|
53 dims(vlen+1:nd) = []; |
|
54 endif |
|
55 nd = length (dims); |
|
56 scale = [1; cumprod(dims(:))]; |
|
57 for i = nd:-1:2 |
|
58 k = (ind >= scale(i)); |
|
59 r = ones (size (ind)); |
|
60 t = zeros (size (ind)); |
|
61 t(k) = floor ((ind(k) - 1) / scale(i)); |
|
62 r(k) = t(k) + 1; |
|
63 varargout{i} = r; |
|
64 ind(k) -= t(k) * scale(i); |
|
65 endfor |
|
66 varargout{1} = ind; |
|
67 for i = nd+1:vlen |
|
68 varargout{i} = ones (size (ind)); |
|
69 endfor |
|
70 else |
|
71 error ("ind2sub: index out of range"); |
|
72 endif |
|
73 else |
|
74 error ("ind2sub: expecting integer-valued index argument"); |
|
75 endif |
|
76 else |
5518
|
77 error ("ind2sub: expecting dims to be an integer vector"); |
4679
|
78 endif |
|
79 else |
6046
|
80 print_usage (); |
4679
|
81 endif |
|
82 |
|
83 |
|
84 endfunction |