MATLAB Class Object Not Updated

前端 未结 2 1911
旧巷少年郎
旧巷少年郎 2021-01-27 06:00

I am writing a simple MATLAB class that has a few properties and a method. The constructor of the class initializes the properties with the default values. The method of the cla

相关标签:
2条回答
  • 2021-01-27 06:14

    Your class needs to inherit from the handle superclass. Try:

    classdef classTest < handle
    properties
        p1
        p2
        p3
        p4
    end
    
    methods
    
        function obj = classTest()
            obj.p1 = 0;
            obj.p2 = 0;
            obj.p3 = [];
            obj.p4 = '';
        end
    
        function obj = updateSomeProperties( obj, p1 )
            obj.p1 = p1;
        end
    end
    end 
    

    This will give,

    >> b = classTest
    
    b = 
    
    classTest with properties:
    
    p1: 0
    p2: 0
    p3: []
    p4: ''
    
    >> b.updateSomeProperties(10)
    
    ans = 
    
      classTest with properties:
    
    p1: 10
    p2: 0
    p3: []
    p4: ''
    
    >> b
    
    b = 
    
    classTest with properties:
    
    p1: 10
    p2: 0
    p3: []
    p4: ''
    
    0 讨论(0)
  • 2021-01-27 06:19

    The issue is that your class is a value class which is passed (even to it's own methods) as a copy. This is the default behavior for MATLAB classes as this is what all fundamental MATLAB datatypes are. We can verify that this is the case by looking at the output of your call to updateSomeProperties(). You will see that the returned result (shown as ans) contains the modification that you expect but these changes are not present in your original object, b. If you wanted to stick with a value class, you would need to return the new object from the method and re-assign the variable when calling the method.

    b = classTest();
    b = b.updateSomeProperties(10);
    

    What you want is a handle class which is always passed by reference. This allows a method to operate on the same object rather than modifying a copy of the original object.

    To do this, you will want to inherit from the built-in handle class.

    classdef classTest < handle
    

    There is a detailed comparison of handle and value classes in the documentation.

    As a side-note, rather than manually setting all default property values in the constructor, it is possible to simply specify these defaults within the properties block itself.

    properties
        p1 = 0;
        p2 = 0;
        p3 = [];
        p4 = '';
    end
    
    0 讨论(0)
提交回复
热议问题