How do properties work in Object Oriented MATLAB?

前端 未结 3 636
花落未央
花落未央 2020-11-29 07:05

I am trying to create a MATLAB class with a member variable that\'s being updated as a result of a method invocation, but when I try to change the property within the class

3条回答
  •  庸人自扰
    2020-11-29 07:53

    Using a Vanilla Class

    When using vanilla class you need to tell Matlab to store a modified copy of the object to save the changes in the property value. So,

    >> a=testprop
    >> a.Request(5); % will NOT change the value of a.numRequests.
    5
    
    >> a.Request(5) 
    5
    
    >> a.numRequests
    ans = 
           0
    
    >> a=a.Request; % However, this will work but as you it makes a copy of variable, a.
    5
    
    >> a=a.Request; 
    5
    
    >> a.numRequests
    ans =
           2
    

    Using the Handle Class

    If you inherit from the handle class, that is

    classdef testprop < handle
    

    then you can write,

    >> a.Request(5);
    >> a.Request(5);
    >> a.numRequests
    ans = 
           2
    

    Update: Using Vanilla Class

    As Kamran notes for the above to work the definition of the Request method in the question's example code needs to be changed to include an output argument of type testprop.

    Thanks Kamran.

提交回复
热议问题