having structures as parameters when entered into methods in a class - matlab

My mate is trying to do this on matlab (Please excuse the terminology. I am not super sure with matlab.)
He is entering two structures which are polynomials into a class as parameters in methods but it will only accept doubles for some reason. hOW do you fix this?
classdef dostuff
properties
polyn %not really sure what this does
end
methods
function r = plus(struct1, struct2)
r = dostuff(addthem(struct1,struct2)); %adds the two polynomials
end
end
end
The error is Undefined function 'dostuff' for input arguments of type 'struct'.
How do you get the class to accept structures (polynomials) as parameters?

The class dostuff does not have a constructor that will accept a struct. So the call to
dostuff(addthem(struct1,struct2))
is trying to call a constructor that doesn't exist. You would need a constructor like
methods
function obj = dostuff(mystruct)
obj = <...>
end
end

Related

Problem with implementing abstract property in Matlab

In Matlab (2017b) I'm trying to implement a superclass with a yet undefined abstract property.
classdef Class_Test1
properties (Abstract=true)
obj
end
end
Subclasses should then implement this property and restrict it to a certain class, e.g.:
classdef Class_Test2 < Class_Test1
properties
obj#double = 123;
end
end
a = Class_Test2; now throws an error:
The property 'obj' restriction defined in class 'Class_Test2' must match
the property definition in base class 'Class_Test1'.
Is there no way to specify the class / type of obj in the implementation of the abstract class or am I missing something?
In the end I would like obj to be abstract in Class_Test1 to implement several subclasses, which will hold objects of different classes in obj.
Any help appreciated ...
MATLAB classes are weird... or in any case very different from what you expect from a class if you've learnt about classes in any other programming language.
One aspect of MATLAB is that it's an interpreted language. Stuff is evaluated when executed, not when compiled. So code doesn't always need to make sense.
So, we can solve your issue like this:
classdef (Abstract) foo
methods
function c = getclass(in)
c = class(in.obj);
end
end
end
The function foo.getclass seems to not make sense, since foo doesn't have a property obj. But because foo is abstract, we're never going to have an object of class foo on which we'll call the getclass method. Whenever getclass is called, it'll be a derived class. So, if we want to use this getclass method, we need to make sure that the derived class has a property obj:
classdef foo_uint8 < foo
properties
obj#uint8 = uint8(1);
end
end
It is now possible to call foo_uint8.getclass:
>> a = foo_uint8;
>> a.getclass
ans =
'uint8'
OK, so after looking into this further it seems that this is a deliberate limitation based on the design of Matlab. I'm not too familiar with OOP in other languages but would be interested to learn if this is an general OOP fundamental or rather Matlab specific.
As a workaround I have come up with the following solution:
classdef (Abstract) Class_Test1 < handle
properties
Obj
end
properties (Abstract = true, Constant)
ObjClass#char
end
methods
function set.Obj(obj_in,in)
if isa(in, obj.ObjClass)
obj_in.Obj = in;
end
end
end
end
... and the implementation ...
classdef Class_Test2 < Class_Test1
properties (Constant)
ObjClass#char = 'double'; % Define the allowed class here ...
end
end
I would still be interested to learn about other possible solutions.

Inheritance in matlab

I am having some trouble with matlab. I am working with b-splines. Sometimes I want to work with the actual spline, while other times I only want to use the so-called basis functions. Without diving into the theory of b-splines, the practical difference is that the when I want to work with the b-spline, I need an extra method and property. I want this property to be initialized by passing it in the constructor.
What I have so far (with most irrelevant methods and properties removed) hopefully roughly demonstrates the behavior that I want:
bsplinespace.m:
classdef bsplinespace < handle
properties
p % polynomial degree
end
methods
function result = bsplinespace(p)
result.p = p;
end
end
end
bspline.m:
classdef bspline < bsplinespace
properties
controlpoints
end
methods
function result = bspline(p, controlpoints)
result.controlpoints = controlpoints;
end
function result = getp(this)
result = this.p;
end
end
end
However, in this scenario the bspline constructor calls the bsplinespace constructor without passing any arguments, causing it to crash:
Not enough input arguments.
Error in bsplinespace (line 8)
result.p = p;
Error in bspline (line 7)
function result = bspline(p, controlpoints)
To be more explicit, what I want is:
One class bsplinespace, which has a constructor which accepts one parameter p
A class bspline, which is the same, but has an extra property and method
Is there an elegant way to implement this?
In your constructor method for bspline, you need to explicitly call the superclass constructor with input argument p:
function result = bspline(p, controlpoints)
result#bsplinespace(p)
result.controlpoints = controlpoints;
end
Otherwise MATLAB will call the superclass constructor with zero input arguments, and you'll get the error you're seeing.
It's a perfectly sensible design, and allows you to control the details of how arguments to the subclass constructor are passed through to the superclass constructor (or not, if you'd like to provide default arguments instead).

Calling class object from a function without insert it to the function in 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.

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.

OOP Matlab inheritance issue with Matlab coder (Simulink MATLAB Function block)

I have defined an abstract base class measurementHandler < handle which defines the interface for all inherited classes. Two subclasses of this class are a < measurementHandler and b < measurementHandler.
I now have a function which should return a handle to an instance of either of these subclasses (depending on the function arguments) to it's caller. Consider something like this:
function returnValue = foobar(index)
if index == 0
returnValue = a();
else
returnValue = b();
end
end
This function is enclosed in a MATLAB Function block in Simulink (2013a). When I try to simulate the system, I get the following error:
Type name mismatch (a ~= b).
Can anybody suggest a workaround for this which still allows me to take advantage of OOP & inheritance when using Simulink?
This kind of pattern is possible in MATLAB Function block only if the "if" condition can be evaluated at compile time. The types cannot be switched at run-time. Can you make the index value a constant at the call site?
The main reason to use this pattern was to iterate over a measurementHandler Array, while these all can have custom implementations. I was able to do this by unrolling the loop with the coder.unroll directive. Example for the enclosing MTALAB Function block:
function result = handleAllTheMeasurements(someInputs)
%#codegen
for index = coder.unroll(1:2)
measurementHandler = foobar(index);
measurementHandler.handleMeasurement(someInputs);
end
result = something;
end
This way, the for loop gets unrolled at compile time and the return type of the function is well defined for each separate call.