MATLAB Class Object Not Updated

前端 未结 2 1931
旧巷少年郎
旧巷少年郎 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: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
    

提交回复
热议问题