Calling class object from a function without insert it to the function in MATLAB - matlab

We have this code in 'Reconstruction the subclass object from a saved struct' from MATLAB OOP documentation.
classdef MySuper
% Superclass definition
properties
X
Y
end
methods
function S = saveobj(obj)
% Save property values in struct
% Return struct for save function to write to MAT-file
S.PointX = obj.X;
S.PointY = obj.Y;
end
function obj = reload(obj,S)
% Method used to assign values from struct to properties
% Called by loadobj and subclass
obj.X = S.PointX;
obj.Y = S.PointY;
end
end
methods (Static)
function obj = loadobj(S)
% Constructs a MySuper object
% loadobj used when a superclass object is saved directly
% Calls reload to assign property values retrived from struct
% loadobj must be Static so it can be called without object
obj = MySuper;
obj = reload(obj,S);
end
end
end
I have a question about obj = MySuper. What is purpose of this line? How we can call MySuper object from this function without insert any object to loadobj function?

You first question is: What is the purpose of the obj = MySuper; line?
The answer is that the obj = MySuper; line initiates the variable obj as an element of the class MySuper. Non-static functions in a class will only run if the first input parameter is an instance of the class, so if obj is not initiated as a MySuper-object, then matlab will look for other functions called reload to run, and if none is found give you an error.
For your second question, I am not 100% sure what you mean. But I hope one of the following points will answer your question:
If you want to make a function that relates to a class, but not to a specific instance of the class, you can make a static function, these can take any input (also (if you want it that way) no input at all) - that is they don't need to have a first input parameter of the specific class.
To run a static function, use the class name followed by a dot and then the function name, so here you would type MySuper.loadobj(S) to run the function with the parameter S.
I would suggest that you try this out with the given example to better get to know the way oop works in matlab, you may for example try:
S.PointX = 1;
S.PointY = 2;
obj = MySuper.loadobj(S)
I hope this answers your questions.

Related

access data returned from a method of a class in other methods

I've got the following class
classdef setting
properties(Constant)
n = setting.get_n;
q = setting.get_q;
end
methods(Static)
function data = load_setting
File = 'Configuration.ini';
I = INI('File',File);
I.read();
data = I.get('UserData'); % struct
end
function n = get_n
data = setting.load_setting;
n = data.m + 2;
end
function q = get_q
data = setting.load_setting;
temp = data.q;
q = fieldnames(temp);
end
end
end
I'd like to know if it is possible to access data returned by load_setting automatically in the rest of the methods defined in the class instead of calling it data = load_setting in each method. Suggestions will be really helpful.
Constants are typically provided by functions in MATLAB. For example, pi is a function. A function that provides constant data that is read from a file could be written like this, using the keyword persistent (code not tested):
function data = config_data
persistent data;
if isempty(data)
File = 'Configuration.ini';
I = INI('File',File);
I.read();
data = I.get('UserData');
end
end
Now the first time you use config_data, it will load the data. Subsequent times it will immediately return the data struct. In the most recent version of MATLAB you can use dot indexing on the return value of a function, so you can do config_data().m or config_data().q and get the relevant field from your data. The function above could process the data further to obtain the q and n values that are computed in your static class methods, so you don't need anything from the setting class, as long as all the data is static.
If you need your constant data to be a class instead of a function (static methods computing values on the fly, or using input values), I would plug the above into your class as the static function load_setting, because that leads to the least amount of work.
there is a way to create a Constant property which you can change it! its through class composition.
first you should define a data class of reference(handle) type :
classdef dataclass<handle
properties
m=3;
n=4;
end
end
then create a Constant data property in your setting class :
classdef setting
properties (Constant)
data=dataclass()
end
methods (Static)
function somefunc()
a=setting();
a.data.n=1;
a.data.m=2;
end
function out=showdata()
out=setting.data;
end
end
end
this way you have a constant reference to the data and when you call A.somefunc() you can change it within all class and all objects of that class.

Program in same OOP style as App Designer

I like the OO programming style that matlabs App Designer uses (or at least the way I'm using it). Now I'm wondering if I can use the same style in my "normal" matlab class.
What I have now:
classdef myClass
properties
myVar;
end
methods
function Main(obj)
obj.myVar = "a";
obj = DoSomething(obj);
disp(obj.myVar) % outputs "c"
end
function obj = DoSomething(obj)
if(obj.myVar == "a")
obj.myVar="c";
else
obj.myVar = "b";
end
end
end
end
Which can be called externally using:
myClassInst = myClass;
myClassInst.Main()
I would like to get rid of all the "obj = " in the classdef, as is possible in App Designer. So something that would look like this:
classdef myClass
properties
myVar;
end
methods
function Main(obj)
obj.myVar = "a";
DoSomething(obj); % Just call the function without "obj = "
disp(obj.myVar) % outputs "a" because I didn't overwrite obj
end
function DoSomething(obj)
if(obj.myVar == "a")
obj.myVar="c";
else
obj.myVar = "b";
end
end
end
end
The equivalent of this seems to work in App Designer. So it appears you can modify variables in a class (instance?) in App Designer, while also being able to access the modified variable without explicitly overwriting your old class instance.
I noticed App Designer has all methods an properties set to (Access = private), though I'm not sure that has anything to do with it. Of course if I set everything to private, then I can't access the Main() method from outside anymore.
So my question is, how can I program in "normal" matlab, the same way as is possible in App Designer?
EDIT:
The following works in App Designer (I left out the methods/properties for the GUI elements):
classdef tmp < matlab.apps.AppBase
properties (Access = private)
myVar; % Description
end
methods (Access = private)
function doSomething(app)
if app.myVar == "a"
app.myVar = "c";
else
app.myVar = "b";
end
end
end
% Callbacks that handle component events
methods (Access = private)
% Code that executes after component creation
function startupFcn(app)
app.myVar = "a";
doSomething(app);
disp(app.myVar); % outputs "c"
end
end
end
You definitely can! All you have to do is inherit from the handle class, as opposed to a value class which is the default for matlab. You can also define private and public methods as in other languages.
The only thing you have to do is:
classdef myclass < handle % this is how you inherit from base class
properties
public_property
end
properties (Access=private)
private_property
end
methods
function obj = myclass() % class constructor
...
end
function public_function()
...
end
end
methods (Access=private)
function private_function()
...
end
end
end
Now every time you pass an object of this class to a function, you are not passing it by value, you are passing by reference (as you might be used to from python) and modifying it's properties modifies them also in the original object.
You need to inherit (< at the top of the class) from a handle class
classdef myClass < handle
properties
var
end
methods
function obj = myClass( varargin )
% Constructor function, called automatically when object is created
end
function someFunction( obj )
obj.randomizeVar(); % Equivalent to randomizeVar( obj );
end
function randomizeVar( obj )
obj.var = rand();
end
end
end
See the documentation for the difference between a "handle" and "value" class:
A value class constructor returns an object that is associated with the variable to which it is assigned. If you reassign this variable, MATLABĀ® creates an independent copy of the original object. If you pass this variable to a function to modify it, the function must return the modified object as an output argument. For information on value-class behavior, see Avoid Unnecessary Copies of Data.
A handle class constructor returns a handle object that is a reference to the object created. You can assign the handle object to multiple variables or pass it to functions without causing MATLAB to make a copy of the original object. A function that modifies a handle object passed as an input argument does not need to return the object.
Moreover, if you edit matlab.apps.AppBase, the class which you app designer code inherits, you can see that the first line is
classdef AppBase < handle
So you are literally doing the same thing, without the AppBase middle-man.

How to run batch jobs in Matlab using parcluster, if I want to run a method of a class

I want to run jobs in Matlab using batch, with parcluster. each job should use an existing class, and run one of it's methods. I can make It work without parcluster, but with parcluster I get an error.
without parpool, this works:
define a class with a simple method:
classdef myclass
properties
prop;
end
methods
% constructor
function obj = myclass()
obj.prop = 0;
end
% add function
function obj = add(obj,a)
obj.prop = obj.prop + a;
end
end
end
create an object and use it's function:
obj = myclass();
obj = add(obj,1);
this works. but when I try to run the same thing in batch I get an error. here is what I'm doing:
c = parcluster();
j = batch(c,#myclass,1,{});
wait(j);
r = fetchOutputs(j);
obj = r{1};
j = batch(c,#add,1,{obj,1});
the last line gives an error:
warning unable to calculate the dependencies of the files:
add
because: file, function or class "add" may not exist.
how can I run class methods in batch?
The most robust way of specifying a method of a class in an anonymous function is to use the dot notation
B = batch(c, #obj.add, 1, {1});
wait(B)
%// Re-assign results to obj (see note below)
obj = fetchOutputs(B);
This helps MATLAB to resolve myclass.add better as it is more explicit. The way that you had written it previously, MATLAB is looking for a regular function named add and is unable to find it. It does not consider the types of the input (which in your case would be required to know that it is a method).
Note: batch will make a copy of your object when you pass it as an input. Because of that, you will need to explicitly grab the output and re-assign to obj because the original obj will not be modified in-place.

MATLAB: save a class property

I'd like to save a particular class property to disk, while ignoring the rest of the class properties. I think MATLAB allows the saveobj method to be overridden for this purpose. However, this saves the class object with only that property attached. I want to save the property itself, without any of the class information.
I might think that a suitable method would look like:
classdef myClass
properties
myProp
end
methods
def b = saveobj(a)
b = a.myProp;
end
def Save(a,fname)
save(fname,'a.myProp');
end
end
end
But neither of these have the desired effect. Can anyone help me, please?
You can overload the save function itself without having to go through saveobj:
classdef myClass
properties
myProp
end
methods
function [] = save(a,fname,varargin)
myProp = a.myProp; %#ok<PROP,NASGU>
save(fname,'myProp',varargin{:});
end
end
end
Then on the command window:
>> foo = myClass();
>> foo.myProp = 4;
>> foo.save('var.txt');
>> bar = load('var.txt','-mat');
>> bar.myProp
ans =
4
The first method (the one involving saveobj) is actually correct. For the purposes of discussion let us consider this simple class:
classdef testclass
properties
x
end
methods
function this = testclass(x)
this.x = x ;
end
function a = saveobj(this)
a = this.x ;
end
end
end
When you ask MATLAB to save an instance of your class, it will use the saveobj method when you call save if one exists. The output of this method can be an object, a struct, an array, whatever. You want to test that this has occurred, and you do something natural like this:
>> obj = testclass('hi')
obj =
testclass with properties:
x: 'hi'
>> save tmp.mat obj
>> clear all
>> load tmp.mat
>> obj
obj =
testclass with properties:
x: []
>>
And this is where I suspect your confusion arises. You expect obj to be a char but instead it's an empty object of class testclass. (You can verify that it is just an instance of the object based on the saved definition of the class, and that it is not created by calling the empty constructor.)
This may seem rather confusing until you understand how loadobj works. In order for MATLAB to know which static method to call on load, it saves the class definition in conjunction with whatever output you are providing from your custom saveobj method. When you call load it then loads the class definition and calls the loadobj static method if one exists. We can test this by modifying the class definition above:
classdef testclass
properties
x
end
methods
function this = testclass(x)
this.x = x ;
end
function a = saveobj(this)
a = this.x ;
end
end
methods( Static )
function this = loadobj(a)
this = testclass(a) ;
end
end
end
If you set a breakpoint in the loadobj method you can verify that the type of a is indeed char as you expect.

MATLAB CLASSES getter and setters

I come from a Java background. I am having issues with classes in Matlab particularly getters and setters. getting a message saying conflict between handle and value class I'm a little lost with what to do so any help for lack of a better word will be helpful.
classdef Person
properties(Access = private)
name;
age;
end
methods
% class constructor
function obj = Person(age,name)
obj.age = age;
obj.name = name;
end
%getters
function name = get.name(obj)
end
function age = get.age(obj)
end
%setters
function value = set.name(obj,name)
end
function value = set.age(obj,age)
end
end
end
Implementation
Since your class is currently a subclass of the default Value class, your setters need to return the modified object:
function obj = set.name(obj,name)
end
function obj = set.age(obj,age)
end
From the documention: "If you pass [a value class] to a function, the function must return the modified object." And in particular: "In value classes, methods ... that modify the object must return a modified object to copy over the existing object variable".
Handle classes (classdef Person < handle) do not need to return the modified object (like returning void):
function [] = set.name(obj,name)
end
function [] = set.age(obj,age)
end
Value vs. Handle
Going a bit deeper, the difference between a Value class and a Handle class lies mostly in assignment:
Assigning a Value class instance to a variable creates a copy of that class.
Assigning a Handle class instance to a variable create a reference (alias) to that instance.
The Mathworks has a good rundown on this topic.
To paraphrase their illustration, the behavior of a Value class is
% p is an instance of Polynomial
p = Polynomial();
% p2 is also an instance of Polynomial with p's state at assignment
p2 = p;
and of a Handle class is
% db is an instance of Database
db = Database();
% db2 is a reference to the db instance
db2 = db;
Quick'n Dirty from the Java perspective:
- "handle" classes are what your mind is set to. proper object instances with pointers to them. use them.
- "value" classes are always returning a full clone of whatever object (which has been modified by what you just did, e.g. setting a name).
the reason they have both in Matlab is that in Matlab you would expect the "value" behaviour natively. Imagine you have a matrix A = [1 2; 3 4], then assign that via B = A. if you now set B(1) = -1 you'd hope that A(1) is still 1, right? this is because matlab keeps track of "copies" and truly creates them as you modify different variables initially set to the same matrix. in OOP you'd have A(1)=-1 now as everythings an object reference.
furthermore, "native" matlab routines dont have a "this/self/me" variable that contains the instance reference to access from within functions. instead, the convention is that the class instance will be prepended to the function's argument list.
so for a function call myclass.mymethod(arg1,arg1), the declaration must be
function mymethod(this, arg1, arg2)
% Note that the name you choose for "this" is arbitrary!
end
mind you, this is the java-perspective (and also my favourite one), the above function call is equivalent to mymethod(myclass,arg1,arg1). this is more native to matlab-style, but somehow makes it harder to see you're calling an objects method.
now, regarding setters/getters: for handle classes, everything feels java-ish now:
classdef MyClass < handle
properties
MyProp;
end
methods
function set.MyProp(this, value) %Note: setMyProp is also valid!
... % do checks etc, trigger calls,
this.MyProp = value;
end
function value = get.MyProp(this)
... % notify, update, triggers etc
value = this.MyProp;
end
end
Of course it goes without saying that you dont need to define a getter if you just want to return the value, i.e. myclassinstance.MyProp will work without any just as well.
Finally, getters/setters for value classes are something that [never encountered me/i never needed] in my 7 years of matlab oop, so my advise would be to go with handle classes and enjoy happy matlab coding :-)
otherwise, the above explanation & official matlab docs is doing the job for value class getter/setters.