Set class property of an instance within class method in MATLAB - matlab

My Objective is:
Using MATLAB, set the property value within one class method, and the property values are different between instances.
My Problem is:
When using SET in the class method, I will change the property value of all instances of this class, which is not what I want. I only want to change the property value of this instance.
About the dynamic property: I think it's used to create a unique property of the instance instead of setting the unique value of a general class property, is that right?
Code example:
classdef Storage
properties
tree = containers.Map('KeyType','int32', 'ValueType','any')
end
methods
function obj = set_tree(obj,period, value)
obj.tree(period) = value;
end
end
end
When setting the value using this method:
st1 = Storage();
st2 = Storage();
st1 = st1.set_tree(10,1);
st2 = st2.set_tree(10,2);
Right now, the value set to st2.tree(10) will override the value set to st1.tree(10), which I am trying to avoid.

The problem you're having is caused by setting a handle class object as a default value for a class property. The relevant documentation says this:
MATLAB® evaluates property default values only once when loading the class. MATLAB does not reevaluate the assignment each time you create an object of that class. If you assign an object as a default property value in the class definition, MATLAB calls the constructor for that object only once when loading the class.
So, for your Storage class above, all of your instances will be using the same default containers.Map object stored in the tree property. And since the containers.Map class is a subclass of the handle class it has reference behavior, which means the copies of the object will all point to the same underlying key/value map. If you want independent objects for each instance, you can initialize the tree property in the constructor:
classdef Storage
properties
tree
end
methods
function obj = Storage()
obj.tree = containers.Map('KeyType','int32', 'ValueType','any');
end
function obj = set_tree(obj, value, period)
obj.tree(period) = value;
end
end
end

Related

Validate property to be a sublclass of an abstract class in MATLAB

I'm brand new to OOP in Matlab, and still fairly green when it comes to OOP in general, but what I do know I learnt in C++.
I'm following the Matlab documentation found here Property class and size validation. I want to validate a property so that it must be a specific class and I'm using the example from the link. This is what my class looks like:
classdef simpoint
...
properties
...
outputType dataType
...
end
...
end
In my code dataType is a class I've written. What's more it's abstract.
I'm getting the error
Error defining property 'outputType' of class 'simpoint':
Class dataType is abstract. Specify a default value for property outputType.
The class dataType is abstract to force the user to implement some methods. I'm trying to use property validation to make sure when outputType is set, the class is a subclass of dataType.
I don't really want to set a default value, because forgetting to set outputType should throw an error.
How can I validate outputType to make sure it is a subclass of dataType? Is there a better way to do this in Matlab?
There is a more elegant solution to this problem, which is apparently not well known.
MATLAB has a concept of Heterogeneous Class Hierarchies. This is just fancy way of explicitly declaring the common root class (abstract or not) so that it can be used for property validation. In practice, all you need to do is to make your abstract class inherit from matlab.mixin.Heterogeneous.
Here is a quick example:
classdef (Abstract) AbstractItem < handle & matlab.mixin.Heterogeneous
end
classdef Collection < handle
properties
items AbstractItem
end
end
Then you have no problem:
>> x = Collection
x =
Collection with properties:
items: [0×0 AbstractItem]
Without the matlab.mixin.Heterogeneous inheritance you would get an error like you described:
Error defining property 'items' of class 'Collection'. Class AbstractItem is abstract. Specify a default value for property items.
Your current code uses the following logic:
Create a new simpoint object
Ah this object needs an outputType property
Initialise the outputType property to be an empty dataType object
Uhoh, we can't instantiate an abstract object - error.
Instead, you could also use setters and getters to validate data types. This removes steps 3 and 4 above, since the initial property value will be [].
classdef simpoint < matlab.mixin.SetGet
properties
outputType
end
methods
% ...
end
methods % Setters and getters
function set.outputType( obj, v )
% When the 'obj.outputType = X' is called, this function is
% triggered. We can validate the input first
assert( isa( v, 'dataType' ) );
% If the assertion didn't error, we can set the property
obj.outputType = v;
end
function v = get.outputType( obj )
% Nothing bespoke in the getter (no not strictly needed), just return the value
v = obj.outputType;
end
end
end
For more informative validation, you could use validateattributes instead of assert.
In this case, the default value of outputType will be [] unless you initialise it in the constructor.
Note, by using matlab.mixin.SetGet to enable setters and getters, I've implicitly made your object a handle. In broader OOP terms, the object is now accessed "by reference" rather than "by value". Read more here.
If you don't want a handle then you can remove the < matlab.mixin.SetGet and, by your own comment, define the setter more explicitly
function obj = set.outputType( obj, v )
% Have to return 'obj' if the class isn't a handle.
% ...
end

How to load a property on demand?

I want to load a property on demand but i cant get it working.
I have a class with a transient property foo. So the property is not stored when the object is saved. When I use a method that is calling the property 'foo', I want that the value of foo is loaded from a separate mat file and stored into the object as long as it is in workspace.
I tried something with get and set methods but cant get it working. Is this possible? Or do I always add a line of code that is loading the property? The following code does not do what I want but it gives an indication what i tried.
In addition, the code below keeps loading the foo.mat file when the property is used. I want to load foo.mat only one time and store it as a property and retrieve the data from there instead of loading. The reason for my question is that the foo property is rather large i.e. a class with many properties in itself. I only want to load it when it is needed and dont want to store it in foobar class itself.
classdef foobar
properties(Transient = true)
foo
end
methods
function value = get.foo(obj)
if isempty(obj.foo)
value = load('foo.mat');
disp('load foo.mat');
end
end
function obj = set.foo(obj,value)
obj.foo = value;
end
end
end
You have two major problems here:
In your get.foo method, once you load the value, you never update the value of foo in the object, so it remains empty.
Even if you tried to update foo in your get.foo method, it would still be empty in the original object because your foobar class is a value class. Methods that modify a value class object have to return the modified object as an output, because they are essentially modifying a copy of the object. A set method of a value class returns a modified object that is used to overwrite the original object, but get methods don't return modified objects (since they aren't generally expected to modify them). To get around that limitation, you'll need the reference-like behavior of a handle class (here's a related question you may want to take a look at for more background).
So, in order to get the behavior you want you'd have to implement foobar as a subclass of the handle class and update the foo field when you first load it:
classdef foobar < handle % Inherit from handle class
properties(Transient = true)
foo
end
methods
function value = get.foo(obj)
if isempty(obj.foo)
value = load('foo.mat');
disp('load foo.mat');
obj.foo = value; % Update foo
end
value = obj.foo; % Return current foo value
end
function set.foo(obj, value) % Return value is unnecessary for handle class
obj.foo = value;
end
end
end
This should now give you the behavior you want (i.e. foo is only loaded when it is first accessed).
Note: Any method that invokes get.foo will initialize foo. One method you may overlook, because it's created by default for a class, is the disp method. The default display for a class object will show the class name followed by a list of non-hidden public properties and their values. Note what happens when I create an object of class foobar from above with and without a semicolon:
>> f = foobar; % Display is suppressed
>> f = foobar
f =
load foo.mat % foo gets initialized...
foobar with properties:
foo: [1×1 struct] % ...because its value is displayed here
If you want to avoid this, you can overload the disp function for your foobar object so that displaying the object doesn't access (and thus initialize) foo. For example, you can add this method to the above foobar class:
function disp(obj)
disp(' foobar object');
end
Now you won't initialize foo when displaying the object:
>> f = foobar
f =
foobar object % foo not yet initialized
>> a = f.foo;
load foo.mat % foo initialized because we accessed it

Force conversion of struct to object in MATLAB loadobj function

I am working with a custom defined class I called "PathObj_Standard". I want to make sure that when I load this class, if the property CalcDate was saved as a cell array it is converted to a standard array. However, I changed the class definition some time ago, so when I use the loadobj function, I am getting a struct instead of an object. The original code I'm using has a lot more properties, so I'd rather not create a new object by assigning property by property from the struct to a new object. Furthermore, I'm also hesitant to change the constructor to accept a struct as an argument.
I tried using the class function inside loadobj, but I am getting a Cannot redefine class 'PathObj_Standard' without a call to 'clear classes' error. Isn't this function supposed to force conversion of a struct to an object? Why doesn't it work within the loadobj function?
classdef PathObj_Standard < handle
properties (SetAccess = protected)
CalcDate;
Name;
end
methods(Static)
function obj=loadobj(s)
if isstruct(s)
obj=class(s,'PathObj_Standard');
else
obj=s;
end
if not(isempty(obj.CalcDate)) && iscell(obj.CalcDate)
obj.CalcDate=cell2mat(obj.CalcDate);
end
end
end
methods
function obj=PathObj_Standard(Name,CalcDate)
obj.Name=Name;
obj.CalcDate=CalcDate;
end
end
The issue is that calling class attempts to create a class which you can't do from within your loadobj. You'll want to call the actual constructor
Also in my experience, the easiest way to construct a class from a struct is to inherit from hgsetget rather than handle as that automatically has the set and get methods of MATLAB's graphics objects and these methods can accept property/values in the form of a struct. In newer versions of MATLAB, you can also use the SetGet mixin
classdef PathObj_Standard < hgsetget
If you do this, you could change your loadobj method to be something like
function obj = loadobj(s)
% Update the input struct as needed
if isfield(s, 'CalcDate') && ~isempty(s.CalcDate) && iscell(s.CalcDate)
s.CalcDate = cell2mat(s.CalcDate);
end
% Call the default constructor
obj = PathObj_Standard();
% Update all properties that were supplied to loadobj
set(obj, s)
end

What makes a property a computed property in Swift

Let's started with the code snippet:
St Foo {
var proA: Int = 0 { // needs initialization
willSet {
print("about to set proA to \(newValue) from \(proA)")
}
didSet {
print("already set proA to \(proA) from \(oldValue)")
}
}
var ProB: Int { // do not needs initialization
return 1
}
}
let foo = Foo()
foo.proA = 23
print(foo.ProB)
Here are some of my personal understandings about the the stored and computed property:
a: Property with only the observer (willSet and didSet) is not a computed property but a stored property (ex. the proA property in the code above).
b: Computed property must not has initialization (See the comments of the code above).
c: setter is kind of equal to the property observer, the property observer is just the setter + the observer to of the before and after mutating.
Questions:
1. I wonder what makes a property a computed property? Is it correct that as long as the property has a getter and return it is a computed property?
2. Are all my understandings (a, b & c) correct? If not, would be nice of you to point out.
3. Why is it not allowed to initialize an computed property? (Please see the figure below) And when I do so the compiler gives out the warning Cannot call value of none-function type "int" What's the meaning of this error?
Thanks a lot.
First, this is about variables, not properties. Any variable can be a computed variable. A property is just one way to use a variable.
I think on the whole you are making a big mistake in putting a stored variable with setter observers side by side with a computed variable. They are unrelated!
Think of a computed variable as something that looks and acts like a variable when you use it — you get and (maybe) set it — but is in fact a function (or a pair of functions). It is just a compact way of calling a function. That's all it is.
A stored variable with observers, on the other hand, is just a stored variable that also has some observers.
Okay, on to your questions:
I wonder what makes a property a computed property? Is is correct that as long as the property has a getter and return it is a computed property?
Yes. It's a computed variable because you declared it using the syntax that makes it a computed variable (with the curly braces).
Are all my understandings (a, b & c) correct? If not would be nice of you to point out
Yes. I think your "c" is quite insightful: a computed variable does not need a setter observer because it has (gasp!) a setter!
Why is it not allowed to initialize an computed property? (Please see the figure below) And when I do so the compiler gives out the warning Cannot call value of none-function type "int" What's the meaning of this error?
There is no sense in which a computed variable "has" a value — it is computed! it's just some functions! — so it makes no sense to assign it an "initial" value.
A stored property is a property of which the property value is stored together with the instance of the class or struct. The value may be changed, but the property can also be a constant. Thus a stored property can be as simple as:
var proA: Int
let proB: Int
var proC: Int = 0
Computed properties do not store a value. Thus you cannot assign a value to a computed property. A Computed property should have a getter that returns a value. I a broad term, you can think of a computed property as a property that returns the value of a function.
Example of Computed Property
var proA: Int {
return proB * proC
}
With regards to your questions:
Computed Property is therefor a property that do not store a value, and contains a get to return the 'computed' value of the property.
a is correct, b computed properties should not have initialization, c if you mean willSet and didSet. Yes they are like observers for when the property's value will change and did change respectively
Since the value of a computed property is not stored and will never be used, the compiler forbids it.
Hope this helps a bit.
I wonder what makes a property a computed property? Is is correct that as long as the property has a getter and return it is a computed property?
If you define get { } inside the property declaration, it makes that property to a computed property.
And it cannot have initial value as when you access the property, it will always call get{} function declared in property.
Are all my understandings (a, b & c) correct? If not would be nice of you to point out
a is correct
b is wrong.
You can not set initial value for computed property.
Because as I explained in question 1, it will always return result of get{} when you need access to the property.
c : 50% right
setter , it can also be used as to store newValue into another private variable and you can do some additional observing logic. So to observe value changes on stored property, you use willSet and didSet
You can define observing logic on computed property (which has getter and setter) on set{} declaration. But main purpose of set {} is to store the value to another variable or for example UserDefaults.
Why is it not allowed to initialize an computed property? (Please see the figure below) And when I do so the compiler gives out the warning Cannot call value of none-function type "int" What's the meaning of this error?
Same answer
Your code makes compiler to be confused
When you set initial value on the property on declaration, the compiler tries to understand it as stored property. But you also defined get{} for this property, and it means it is computed property and should always return 22 when you access the property. So you should remove one of two.
a. Yes,a property with only observer is a stored property not a computed property.Beacuase property observer tracks the value of a property whose value has initialised previously & it's now changing ,that's a stored property. It's not applicable for a computed property since it has no predefined value
b. computed property is a property whose value depends on other variables, we should declare only those properties as computed property , who needs to be computed using value of another variables ,so it's value cannot be initialised in advance.
for e.g. - If we have 2 variables a & b. we need their addition value , so a variable named 'sum' is used , then sum will be declared as a computed property & its get{} block will return (a+b) that's sum of a & b & the value of sum variable.Then in this case we can't initialise property 'sum'
in advance because it will be computed using a & b.
c. Setter is not an observer it sets value of another variable or performs some actions related to other variables whereas a property observer tracks changes in value of its associated variable itself. for e.g. it's meaningless to use a property observer for variable 'sum' as described in point b .

create array of objects of a class in another class MATLAB

I am trying to create an array of objects of a class Cell in another class Systemin MATLAB. The classCell` is:
classdef Cell
properties
ID;
EntityID;
ZoneID;
NeighborID;
State;
nextChangeTime;
end
methods
% Define the constructor
function obj = Cell()
obj.ID = zeros(1);
obj.EntityID = zeros(1);
obj.ZoneID = zeros(1);
obj.NeighborID = zeros(1);
obj.State = zeros(1);
obj.nextChangeTime = zeros(1);
end
end
Now I have another class System. I try to make an array of Cell objects like this:
classdef System
properties
Cells;
end
methods
function obj = System(dimx,dimy)
obj.Cells(dimx,dimy) = Cell();
end
end
But I think I am using the wrong format. Not sure if this is possible. Any suggestions on how to accomplish this would be appreciated.
In order to be able to create arrays of objects of user-defined class (e.g. Cell class), it is convenient to have the default constructor for the user-defined class. The default constructor is the one that takes no arguments (i.e. when nargin==0). When creating arrays, the implicit initialization of the array's objects is done by this constructor. If this constructor is missing, trying to build arrays by "extending" a scalar object will generate an error.
Another way of creating arrays of objects (without defining a default constructor) is by using horzcat, vertcat and cat.
Aaaaand... when accessing the properties of an object, don't forget to mention the object you're accessing:
obj.Cells = Cell.empty(0,0); % Force the type of empty Cells to Cell class
obj.Cells(dimx,dimy) = Cell();