1

I tried to change an attribute value of a class by invoking one of its member function:

p1 = tank();
p1.checkOri(p1);

And in the class definition, I have that static method:

classdef tank
    properties
        value
        ...
    end

    methods 
        ...

    methods (Static)
        function obj = checkOri(obj)
            if (CONDITION) %the thing I want it to do
                obj.value = EXPRESSION;
                ...

Yet this checkOri method is not working. But if I write this method in the main file, or to say altering the value of p1-the instance of class tank-it works perfectly:

p1 = tank();
p1.checkOri(p1);
if (CONDITION) %the thing I want it to do
    p1.value = EXPRESSION;

It works perfectly.

I wonder what caused this. From my experience with other programming languages, invoking method should have worked, is it because of some tricks with Matlab syntax or static method? How could I fix it so that this method would work?

Amarth Gûl
  • 1,040
  • 2
  • 14
  • 33

2 Answers2

1

So, as @Navan in the comment said, handle class could be a solution.

It appears Matlab has a similar parameter concept with Java and C++, arguments modified in a function/method only remains that modification inside the function/method.

For this class, I simply added < handle in the head of class definition and it worked:

classdef tank < handle
properties
    ...

But I am not sure if that is the only solution, there might be better ways to do this. So I'll leave that question open, you are more than welcomed to post your opinion:D

Amarth Gûl
  • 1,040
  • 2
  • 14
  • 33
1

In MATLAB, the call

p1.checkOri();

is equivalent to

checkOri(p1);

In both cases, the class method checkOri is called for the class of object p1, passing p1 as first argument to the function by value.

Because p1 is passed by value, any changes made to it inside the function are not seen by the object in the calling workspace. Therefore, one typically does

p1 = checkOri(p1);

This way, the object that was passed by value and modified inside the function is passed back out and assigned to the variable that held the original object.

If the method is written as follows:

function obj = checkOri(obj)
%...
end

then MATLAB will optimize the above function call such that no copy of the object is actually made. Note that both in the function declaration and in the function call, the input and output variable is the same.

As already discovered by OP, the above does not hold for handle classes, classes that inherit from handle. These classes act as if they are always passed by reference, and any change made to them in any workspace will be reflected in all other copies in other workspaces.

Also assigning to a member variable does not follow the above, such that

p1.value = 0;

modifies object p1.

For more information on the difference between value classes and handle classes see this other question.

Cris Luengo
  • 55,762
  • 10
  • 62
  • 120