sub2ind() convenience patch
Etienne Grossmann <[email protected]> Sat, 29 May 2004 20:39:34 -0400
| Newsgroups | gmane.comp.gnu.octave.sources |
|---|---|
| Message-ID | <[email protected]> |
Hi all,
I propose the following patch so that does not gripe about the size of
its index arguments, as long as the number of elements is right.
With this patch, code to reshape index lists passed to sub2ind()
becomes unnecessary. Advantage: shorter code.
For example,
octave:34> sub2ind ([3,4,2],[1 3 2 3],[1 2 4 4],[2 1 2 2])
ans =
13 6 23 24
octave:35> sub2ind ([3,4,2],[1 3 2 3],[1 2 4 4],[2 1 2 2]')
error: sub2ind: all index arguments must be the same size
error: evaluating if command near line 49, column 6
error: evaluating if command near line 42, column 4
error: evaluating if command near line 41, column 2
error: evaluating for command near line 39, column 7
error: evaluating if command near line 33, column 5
error: evaluating if command near line 32, column 3
error: called from `sub2ind' in file `/usr/share/octave/2.1.57/m/general/sub2ind.m'
octave:35> mysub2ind ([3,4,2],[1 3 2 3],[1 2 4 4],[2 1 2 2]')
ans =
13 6 23 24
The overhead seems reasonable or negative (!) (timing of mysub2ind
is on the right).
======================================================================
octave:57> T = 100; szs = [3 5 4];
for N=[5 10 50 100 1000, 10000],
N
i1 = 1+floor(szs(1)*rand(1,N));
i2 = 1+floor(szs(2)*rand(1,N));
i3 = 1+floor(szs(3)*rand(1,N));
tic;
for i = 1:T,
sub2ind (szs,i1,i2,i3);
end; tt=toc/T; tic;
for i = 1:T,
mysub2ind (szs,i1,i2,i3);
end;
[tt, toc/T]
end
N = 5
ans =
0.0016043 0.0015547
N = 10
ans =
0.0015739 0.0013806
N = 50
ans =
0.0016303 0.0014407
N = 100
ans =
0.0017061 0.0016547
N = 1000
ans =
0.0026176 0.0024954
N = 10000
ans =
0.012621 0.013198
======================================================================
Just my 2c contribution,
Etienne
======================================================================
--- /usr/share/octave/2.1.57/m/general/sub2ind.m 2004-04-11 23:29:44.000000000 -0400
+++ ./mysub2ind.m 2004-05-29 20:10:50.000000000 -0400
@@ -46,9 +46,9 @@
error ("sub2ind: index out of range");
endif
else
- if (all (size (first_arg) == size (arg)))
+ if (prod (size (first_arg)) == prod (size (arg)))
if ((i > nd && arg == 1) || (arg > 0 & arg <= dims(i)))
- ind += scale(i-1) * (arg - 1);
+ ind(:) += scale(i-1) * (arg(:) - 1);
else
error ("sub2ind: index out of range");
endif
======================================================================
--
Etienne Grossmann ------ http://www.cs.uky.edu/~etienne