matlab

MATLAB order of execution for assignments


Why does

x = 1:7;
x(1:8) = 1:9;

throw

Unable to perform assignment because the left and right sides
have a different number of elements.

rather than

Index exceeds the number of array elements. Index must not
exceed 7.

It's the case in Python: first, evaluate to right of =, then to left of =, then the =:

import numpy as np
x = np.arange(7)
x[7] = np.arange(8)[8]  # next try `[8]` -> `[7]`

(modified example as 0:7 == 0:6 == 0:999 when not indexing individual elements)


Solution

  • I don’t think you can derive an “execution order” from the error messages. Python in your example just happens to throw one error before the other.

    In MATLAB, however, we have the function subsasgn, which is called for custom classes for the syntax x(s) = y. This shows that the indexing on the left-hand side and the assignment are a single operation, you can’t do the one without the other. The indexing on the left-hand side does not trigger an evaluation of the indexed array, we don’t read what is currently there, we just write into those places.