Ind2sub behavior different in matlab and octave

It seems like ind2sub behaves differently in matlab and octave. I’m not sure I understand what’s happening, but at least I can report the discrepancy.

Matlab R2021b allows this:

>> ind2sub(1, [1 2])
ans =
     1     2

octave 6.4 gives an error:

octave:1> ind2sub(1, [1 2])
error: ind2sub: index out of range

I’m not sure if I’m missing something. But I’d guess that a variable of size 1 is a scalar.
Even if Matlab doesn’t error at this call, it will error when these row indices are used to index a scalar later on.
If those row indices aren’t used to index a scalar, the size of the array for which they are intended should be passed as the first argument to sub2ind. In that case, the command should be working both in Matlab and in Octave.

Is there a use case where Matlab’s result would actually be “more correct”?

I can sort of see the logic in what Matlab’s doing, but I’m not finding any documetation to justify it as more than ‘unintentional matlab behavior’. e.g., using Matlab 2021a:

>> r = ind2sub(1,2)
r =
     2

>> [r c] = ind2sub(1,2)
r =
     1
c =
     2

>> [r c p] = ind2sub(1,2)
r =
     1
c =
     1
p =
     2

>> idx = sub2ind(1,r,c,p)
Error using sub2ind (line 29)
Size vector must have at least 2 elements. 

similarly, for a non-scalar:

>> a = magic (3);

>> [r]=ind2sub(size(a),10)
r =
    10

>> [r c]=ind2sub(size(a),10)
r =
     1
c =
     4

>> [r c p]=ind2sub(size(a),10)
r =
     1
c =
     1
p =
     2

>> [r c p]=ind2sub(size(a),11)
r =
     2
c =
     1
p =
     2

>> ind = sub2ind(size(a),r,c,p)
Error using sub2ind (line 73)
Out of range subscript. 

>> a(10)
Index exceeds the number of array elements. Index must not exceed 9. 

>> a(1,1,2)
Index in position 3 exceeds array bounds. Index must not exceed 1. 

sub2ind is apparently telling you where the next one would go, assuming the given size is ‘locked’ and extension only occurs on the last specified dimension.

If this is documented, we can try to support it as a compatibility concern, but otherwise I think priority is going to be pretty low unless it’s a trivial hack. (and since it’s a compiled function, not just an m-file, there’s a smaller pool of developers to draw from for that fix)

1 Like

Well, that didn’t take too long to come up with an example where this could actually be useful. :wink:
I only thought of indexing to return a value but forgot indexing assignments…
E.g.:

>> a = 1:3
a =
     1     2     3
>> a(4) = 4
a =
     1     2     3     4

In that case, “out of range” indexing is actually fine.

Could you please open a bug report for this on savannah?

Absolutely, I will reference this thread.

Here’s the bug report GNU Octave - Bugs: bug #62184, ind2sub behavior different in... [Savannah]

2 Likes

As a help for future readers of this thread, a fix was made for this bug report which will be part of the 8.1 release of Octave.