Ask an expert. Trust the answer.

Your academic and career questions answered by verified experts

How do properties work in Object Oriented MATLAB?

Date: 2022-07-05 10:48:01

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 it (apperently, from what I understood from MATLAB's memory management) creates a copy of the object and then modifies it, leaving the original object's property untouched. 

 

classdef testprop  
    properties  
        numRequests=0;  
    end  
    methods  
        function Request(this, val)  
            disp(val);  
            this.numRequests=this.numRequests+1;  
        end  
    end  
end  

 

 >> a=testprop;
>> a.Request(9);
>> a.Request(5);  
>> a.numRequests  

ans = 0  

Answers: 

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

 


Why Matlabhelpers ?

Our Matlab assignment helpers for online MATLAB assignment help service take utmost care of your assignments by keeping the codes simple yet of high-quality. We offer the most reliable MATLAB solutions to students pursuing their Computer Science course from the Monash University, the University of Sydney, the University of New South Wales, the University of Melbourne; to name a few. Approach us today for best Matlab solutions online!

whatsApp order on matlabhelpers.com

telegram order on matlabsolutions.com