MATLAB always makes a copy when you assign an object, or pass an object to a function. Here's another example of the same thing, but with a simple array:
a = [1 2 3];
b = a;
b(2) = 99;
disp(a)
which prints
- that is, a has not changed. In just the same way, myObj has been copied and not changed in your code. In general, to change the value of an element of an array or a property of an object, the name of the array or object must appear on the left side of an assignment.
Although this is different to some languages, it's an enormously valuable aspect of MATLAB, and must have saved vast amounts of programmer time over the years. It's consistent, and it entirely avoids a significant class of bugs.
This sounds inefficient, but it isn't - the copy is only made when it's actually necessary.
You can override the default and have the behaviour you are used to by declaring your class to be a handle class. For consistency with the rest of the language this is best avoided, but there are situations where a handle class is called for. For more details see this part of the documentation.
Best Answer