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. |
5642
|
23 ## @seealso{sub2ind} |
4679
|
24 ## @end deftypefn |
|
25 |
|
26 ## Author: Paul Kienzle <pkienzle@kienzle.powernet.co.uk> |
|
27 ## Adapted-by: jwe |
|
28 |
|
29 function varargout = ind2sub (dims, ind) |
|
30 |
|
31 if (nargin == 2) |
6050
|
32 if (isvector (dims) && all (round (dims) == dims)) |
|
33 if (isnumeric (ind) && all (round (ind) == ind)) |
4679
|
34 ntot = prod (dims); |
6050
|
35 if (all (ind > 0 & ind <= ntot)) |
4679
|
36 nd = length (dims); |
|
37 if (nargout > 0) |
|
38 vlen = nargout; |
|
39 else |
|
40 vlen = 1; |
|
41 endif |
|
42 if (nd > vlen); |
|
43 dims(vlen) = prod (dims(vlen:nd)); |
|
44 dims(vlen+1:nd) = []; |
|
45 endif |
|
46 nd = length (dims); |
|
47 scale = [1; cumprod(dims(:))]; |
|
48 for i = nd:-1:2 |
|
49 k = (ind >= scale(i)); |
|
50 r = ones (size (ind)); |
|
51 t = zeros (size (ind)); |
|
52 t(k) = floor ((ind(k) - 1) / scale(i)); |
|
53 r(k) = t(k) + 1; |
|
54 varargout{i} = r; |
|
55 ind(k) -= t(k) * scale(i); |
|
56 endfor |
|
57 varargout{1} = ind; |
|
58 for i = nd+1:vlen |
|
59 varargout{i} = ones (size (ind)); |
|
60 endfor |
|
61 else |
|
62 error ("ind2sub: index out of range"); |
|
63 endif |
|
64 else |
|
65 error ("ind2sub: expecting integer-valued index argument"); |
|
66 endif |
|
67 else |
5518
|
68 error ("ind2sub: expecting dims to be an integer vector"); |
4679
|
69 endif |
|
70 else |
6046
|
71 print_usage (); |
4679
|
72 endif |
|
73 |
|
74 |
|
75 endfunction |