This is a question about the MATLAB language. I am going through the MathWorks "Onramp" tutorial, and I have noticed a strange "assignment by reference" behavior (for lack of a better term) that is counter to my expectations.
v1 = [4 6 1 3 4 9 5];
I think that in the below, it first evaluates the parenthetical expression, which generates a logical array [1 0 1 1 1 0 0], which then indexes v1
to get the result. So far so good.
>> v1(v1 < 5)
ans =
4 1 3 4
The below is what surprises me. If you run it, you will see that ans (the default result variable, sort of an anonymous variable) acquires the value [4 1 3 4]
which is the value of the left-hand side of the statement. I would expect the assignment to only write to ans, but instead it passes through by reference and writes to the referent array v1
.
>> v1(v1 < 5) = 1
v1 =
1 6 1 1 1 9 5
Of course, this is similar to other languages. In print a[3]
the syntax means we get the value of a[3]
, but in a[3] = 1
the syntax means we assign a new value to a[3]
. In that sense, the only "new" part is that MATLAB allows more advanced indexing expressions than most languages.
What's confusing here is that MATLAB clearly evaluates the expression both ways. It gets the indexed values and stores them in ans, but then it ignores that and puts the righthand values into the locations referred to by the index.
I don't see how it could do this without evaluating the expression twice, or doing other magic behind the scenes. I don't feel like I have a grasp on the order/rules of evaluation.