Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do properties work in Object Oriented MATLAB?

People also ask

What Does properties do in MATLAB?

Properties contain object data. Classes define the same properties for all object, but each object can have unique data values. Property attributes control what functions or methods can access the property. You can define functions that execute whenever you set or query property values.

What is properties in object-oriented programming?

A property, in some object-oriented programming languages, is a special sort of class member, intermediate in functionality between a field (or data member) and a method.

How do I add a property to an object in MATLAB?

P = addprop( A , PropertyName ) adds a property named PropName to each object in array A . The output argument P is an array of meta. DynamicProperty objects that is the same size as A . Dynamic properties exist only on the specific instance for which they are defined.


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.


You have to remember that syntactically in Matlab, you're probably closer to C, than C++ or Java, at least with respect to objects. So, of you want to change the "contents" of a value object (really just a special struct), you need to return the object from the function.

Azim was correct to point out that if you want Singleton behavior (which, from your code, you seem to), you need to use a "handle" class. Instances of classes that derive from Handle all point to a single instance, and operate only on it.

You can read more about the differences between Value and Handle classes.


I made the class testprop and tried to excute the code which Azim suggested but it did not work. When I executed the following command:

a=a.Request(1)

The following error was generated:

??? Error using ==> Request Too many output arguments.

I think the problem is that we did not determine any output when declaring Request method. So we should change it to:

function this = Request(this, val)

and now:

>> a = testprop;
>> a = a.Request(1);        
>> a.numRequests

ans = 1