arraysmatlaboctavematrix-indexing

Does Matlab accept non-integer indices?


Of course not! ...Or does it? Let's do some tests.

Define x = [10 20 30 40 50]. Then any of the following statements, as expected, gives an error in Matlab (Subscript indices must either be real positive integers or logicals):

>> x(1.2)
>> x(-0.3)
>> x([1.4 2 3])
>> x([1.4 2.4 3.4])
>> x([1.4:4])
>> x(end/2)

However, non-integer values are accepted in colon indices. All of the following work in recent Matlab versions, although with a warning (Integer operands are required for colon operator when used as index).

>> x(1.2:3)
ans =
    10    20

>> x(0.4:3)
ans =
    10    10    20

>> x(0.6:3)
ans =
    10    20    30

>> x(1.2:0.7:5)
ans =
    10    20    30    30    40    50

>> x(-0.4:3)
ans =
    10    10    20    30

It also works if the colon expression includes end:

>> x(1.5:end-2)
ans =
    20    30

>> x(1.5:end/6:end-1)
ans =
    20    20    30    40

On the other hand, the following do not work, and give the same error as above:

>> x(-0.6:2)
>> x(-0.5:2)

The observed behaviour can be summarized as follows:

Similar behaviour is seen in recent versions of Octave, except that:

Other than this, the results are the same as in Matlab, and a warning is also issued (Non-integer range used as index).

The warnings and the fact that Octave works similarly as Matlab suggest that this is intended behaviour. Is it documented somewhere? Can anyone give more information or shed some light on this?


Solution

  • Additional observations:

    Theories:

    Official comments: