Matlab - object orientated with abstract Interface - How creating object? - matlab

Hello lovely community,
i am quite new here, but still hope someone can help me out. I just worked a bit with Matlab in the past and want to do a new project. Earlier I just stored all in one Matlab file and didn't had the need to use classes. This has changed now, so I hope someone can explain me what I did wrong.
My desire is to create the project object based. Therefore I started creating new folders in the main folder:
C:\Users\Luftfahrt\MAV\
The folder names are:
+Data
+Model
After I read the first chapters of
A guide to MATLAB orientaded programming
I figured out that with the plus symbol I am creating public objects. Exactly as I want. In each folder I inserted an abstract Interface and a child for it.
DataLoaderIF
classdef DataLoaderIF< handle
methods (Abstract=true)
Data = LoadData(Asset,Start,End)
Status = getStatus(Obj)
Info = getInfo(Obj)
end
end
When i run this code above he is telling me that Abstract classes cannot be instantiated, but I did it exactly as in the book. Maybe I thought, it is stupid run code from an abstract interface, so that there is no problem, is that true?
DataLoader
classdef DataLoader < DataManager.DataLoaderIF
%Inheritent from DataLoaderIF. Is setting parameter and Importing
properties (Access=protected)
mStatus =-1; %nothing done
mInfo ='Import'; %
mData; %saving the imported data
mCollector; %to save the prices after structuring
end
methods
%creating the constructor
function Obj = DataManager
function getStatus(Obj)
mStatus=1;
end
function getInfo(Obj)
Info='Import';
mInfo= Info;
end
function LoadData(Asset,Start,End)
connection = yahoo;
mData= fetch(connection, Asset, Start,End, 'd');
close(connection)
%'JPY=X', '01-Jun-2011', datestr(now,'dd-mmm-yyyy'), 'd');
mCollector= [{'date' 'open' 'high' 'low' 'close' 'volume' 'adj-close'}
cellstr(datestr(mData(:,1))) num2cell(mData(:,2:end))];
end
end
What I wanted to do now is to create an Object and then give this Object the variables to perform the fetch. But how can I instantiate now the Object? He says my constructor is false.
Someone has some ideas?
P.S. I already looked here Documentation Matlab, but this didn't help me out.
Thanks a lot!

It is not clear what you want to do exactly and why you need an abstract class then a derived one, but assuming you really need all that for more purpose than you described, take the following into account:
By definition in OOP, an abstract class cannot be instantiated. It is only a basic framework for the different classes which will inherit from it, and you can only instantiate these inheriting classes. abstract classes are only useful if the different inheriting classes represent different objects but need to share a set of (almost) common methods. If not, forget the 'abstract' parent and just design the class that does what you need.
Be careful with the classes which inherit from the handle class. In Matlab they behave differently than the value classes. Read this article and decide which type you want.
If you decide to use a handle class, consider the following very important factor Initialising property value:
Initializing Properties to Unique Values
MATLAB assigns properties to the specified default values only once
when MATLAB loads the class definition. Therefore, if you initialize a
property value with a handle-class constructor, MATLAB calls this
constructor only once and every instance references the same handle
object. If you want a property value to be initialized to a new
instance of a handle object each time you create an object, assign the
property value in the constructor.
Now with all that in mind, below is a version of your class that does run, and that you can instantiate as below:
>> dl = DataLoader
dl =
DataLoader with no properties.
>> dl.getInfo
ans =
Import
>> dl.getStatus
ans =
-1
>> dl.LoadData(1,2,3) %// etc ...
The class definition is as follow
classdef DataLoader < DataLoaderIF
properties (Access=protected)
mStatus %// nothing done
mInfo %//
mData %// saving the imported data
mCollector %// to save the prices after structuring
end
methods
%// Constructor (and initialise default value). For classes which
%// inherit from the "handle" class it is very important to
%// intialise your default values IN THE CONSTRUCTOR, and NOT in
%// the property definition.
function obj = DataLoader
obj.mStatus = -1 ;
obj.mInfo = 'Import' ;
obj.mData = [] ;
obj.mCollector = [] ;
end
function Status = getStatus(obj)
Status = obj.mStatus ;
end
function Info = getInfo(obj)
%// a "get" type of function should not assign value, only
%// return information about the object.
Info = obj.mInfo ;
end
%// the "obj" parameter has to be the first parameter of the
%// function in it's signature.
function LoadData(obj,Asset,Start,End)
%// Put function help here
%// I don't know what this part of the code is supposed to do
%// so I leave it as it is. Be aware that the fucntion "fetch"
%// will have to be accessible in your context or the function
%// will error
connection = 'yahoo' ;
obj.mData = fetch(connection, Asset, Start , End, 'd') ;
close(connection)
obj.mCollector= [{'date' 'open' 'high' 'low' 'close' 'volume' 'adj-close'}
cellstr(datestr(obj.mData(:,1))) num2cell(obj.mData(:,2:end))];
%// Here do your own test with your own conditions to decide
%// what the status of the object should be.
if ~isempty(obj.mData) && ~isempty(obj.mCollector)
obj.Status = 1 ;
end
end
end
end
You seemed a bit confused on some concept of OOP. If your first contact with OOP is through Matlab I totally understand where you come from. I had the same experience and my understanding of OOP was wrong for many years (my OOP code was very poor and inefficient too as a result), until I properly learned my way in C++ and .Net. These last two languages are real OOP languages (I know, not the only ones, or even better one, I don't want to start a debate), in the sense that you need to understand the OOP concepts to get anything out of them. On the other hand, you can spend your life doing wonderful things on Matlab and remain blissfully unaware of what even OOP means.
OOP capability was introduced in Matlab as a "convenience" for programmers who missed this way of structuring their code. The first implementations were very clunky and unpractical (raise your hand if you remember having to code each and every one of your subassign, subsref, display, get, set etc for each single object !!). It has been drastically improved since then, until it is now something worth the extra coding effort if you want to get the benefit of OOP organisation (code reuse, polymorphism, inheritance etc ...). However, to this day the OOP syntax in Matlab remain un-instinctive at first even for OOP veterans (why the hell do we have to declare the object itself as the first parameter of the function, is the compiler so blind it does't see the function is in the class definition?). You just have to get used to it first, then it gets ok.
The Matlab documentation on OOP is mostly oriented to these veterans. It explains to people who knows OOP on another languages how to apply the concepts in the Matlab specific syntax. It is not at all a very good guide for pure beginners.
This (longer than I wanted, sorry) blurb, was to try to explain that:
If you need to learn OOP concepts, train yourself with another language first. (seriously, even with the learning curve of learning another language, you'll loose less time than with the trial and error approach on Matlab).
If you do not have a definite identified need for OOP code in Matlab, do not insist. You can do a lot of things (in fact almost everything) in Matlab without resorting to classes (at least not knowingly, of course you will use the base Matlab classes in the background, but you can use and maintain your car for many years without necessarily having an intimate knowledge of its every component).

Related

how single and double type variables work in the same copy of code in Matlab like template in C++

I am writing a signal processing program using matlab. I know there are two types of float-pointing variables, single and double. Considering the memory usage, I want my code to work with only single type variable when the system's memory is not large, while it can also be adapted to work with double type variables when necessary, without significant modification (simple and light modification before running is OK, i.e., I don't need runtime-check technique). I know this can be done by macro in C and by template in C++. I don't find practical techniques which can do this in matlab. Do you have any experience with this?
I have a simple idea that I define a global string containing "single" or "double", then I pass this string to any memory allocation method called in my code to indicate what type I need. I think this can work, I just want to know which technique you guys use and is widely accepted.
I cannot see how a template would help here. The type of c++ templates are still determined in compile time (std::vector vec ...). Also note that Matlab defines all variables as double by default unless something else is stated. You basically want runtime checks for your code. I can think of one solution as using a function with a persistent variable. The variable is set once per run. When you generate variables you would then have to generate all variables you want to have as float through this function. This will slow down assignment though, since you have to call a function to assign variables.
This example is somehow an implementation of the singleton pattern (but not exactly). The persistent variable type is set at the first use and cannot change later in the program (assuming that you do not do anything stupid as clearing the variable explicitly). I would recommend to go for hardcoding single in case performance is an issue, instead of having runtime checks or assignment functions or classes or what you can come up with.
function c = assignFloat(a,b)
persistent type;
if (isempty(type) & nargin==2)
type = b;
elseif (isempty(type))
type = 'single';
% elseif(nargin==2), error('Do not set twice!') % Optional code, imo unnecessary.
end
if (strcmp(type,'single'))
c = single(a);
return;
end
c = double(a);
end

How to generate method parameters based on class parameters for Matlab unit tests

A program I am working on performs calculations that involve objects that can only have several possible sets of values. These parameter sets are read from a catalogue file.
As an example say the objects are representing cars and the catalogue contains a value set {id: (name, color, power, etc.)} for each model. There are however many of these catalogues.
I use Matlab's unittest package to test if the calculations fail for any of the property combinations listed in the catalogues. I want to use this package, because it provides a nice list of entries that failed. I already have a test that generates a cell array of all ids for a (hardcoded) catalogue file and uses it for parameterized tests.
For now I need to create a new class for each catalogue file. I would like to set the catalogue file name as a class parameter and the entries in it as method parameters (which are generated for all class parameters), but I cannot find a way to pass the current class parameter to the local method for creating the method parameter list.
How can I make this work?
In case it is important: I am using Matlab 2014a, 2015b or 2016a.
I have a couple thoughts.
Short answer is no this can't be done currently because the TestParameters are defined as Constant properties and so can't change across each ClassSetupParameter value.
However, to me creating a separate class for each catalogue doesn't seem like a bad idea. Where does that workflow fallover for you? If desired you can still share code across these files by using a test base class with your content and an abstract property for the catalogue file.
classdef CatalogueTest < matlab.unittest.TestCase
properties(Abstract)
Catalogue;
end
properties(Abstract, TestParameter)
catalogueValue
end
methods(Static)
function cellOfValues = getValuesFor(catalog)
% Takes a catalog and returns the values applicable to
% that catalog.
end
end
methods(Test)
function testSomething(testCase, catalogueValue)
% do stuff with the catalogue value
end
function testAnotherThing(testCase, catalogueValue)
% do more stuff with the catalogue value
end
end
end
classdef CarModel1Test < CatalogueTest
properties
% If the catalog is not needed elsewhere in the test then
% maybe the Catalogue abstract property is not needed and you
% only need the abstract TestParameter.
Catalogue = 'Model1';
end
properties(TestParameter)
% Note call a function that lives next to these tests
catalogueValue = CatalogueTest.getValuesFor('Model1');
end
end
Does that work for what you are trying to do?
When you say method parameters I assume you mean "TestParameters" as opposed to "MethodSetupParameters" correct? If I am reading your question right I am not sure this applies in your case, but I wanted to mention that you can get the data from your ClassSetupParameters/MethodSetupParameters into your test methods by creating another property on your class to hold the values in Test[Method|Class]Setup and then referencing those values inside your Test method.
Like so:
classdef TestMethodUsesSetupParamsTest < matlab.unittest.TestCase
properties(ClassSetupParameter)
classParam = {'data'};
end
properties
ThisClassParam
end
methods(TestClassSetup)
function storeClassSetupParam(testCase, classParam)
testCase.ThisClassParam = classParam;
end
end
methods(Test)
function testSomethingAgainstClassParam(testCase)
testCase.ThisClassParam
end
end
end
Of course, in this example you should just use a TestParameter, but there may be some cases where this might be useful. Not sure if its useful here or not.

about matlab's Adaptfilt.<algorithm> function

Matlab's DSP toolbox has a function called adaptfilt., where calling adaptfilt is not enough, but you must add the .< algorithm> where the algorithm can be one of the many things, which we can view using help adaptfilt. What kind of Matlab structure has been used here (or what is the . operator and how can I make my own function that has to be called using a dot).
Also, the result of doing, say, adaptfilt.fdaf, gives a result that seems like a structure. How can I view all the elements of this structure (that is, if there are any more members besides the values that are returned on the screen by the function itself)?
adaptfilt is a class definition, of which fdaf is a member. Then, you use the dot operator to access the static member of the class. See Static Methods in the MATLAB documentation. In summary, to define a similar function yourself use
classdef MyClass
...
methods(Static)
function y = yourFunc(x)
...
end
end
end
The result you're getting from adaptfilt.fdaf is in fact an object. The adaptfilt.fdaf documentation page outlines the members of the object.

What does the . operator do in matlab?

I came across some matlab code that did the following:
thing.x=linspace(...
I know that usually the . operator makes the next operation elementwise, but what does it do by itself? Is this just a sub-object operator, like in C++?
Yes its subobject.
You can have things like
Roger.lastname = "Poodle";
Roger.SSID = 111234997;
Roger.children.boys = {"Jim", "John"};
Roger.children.girls = {"Lucy"};
And the things to the right of the dots are called fields.
You can also define classes in Matlab, instatiate objects of those classes, and then if thing was one of those objects, thing.x would be an instance variable in that object.
The matlab documentation is excellent, look up "fields" and "classes" in it.
There are other uses for ., M*N means multiploy two things, if M, N are both matrices, this implements the rules for matrix multiplication to get a new matrix as its result. But M.*N means, if M, N are same shape, multiply each element. And so no like that with more subtleties, but out of scope of what you asked here.
As #marc points out, dot is also used to reference fields and subfields of something matlab calls a struct or structure. These are a lot like classes, subclasses and enums, seems to me. The idea is you can have a struct data say, and store all the info that goes with data like this:
olddata = data; % we assume we have an old struct like the one we are creating, we keep a reference to it
data.date_created=date();
data.x_axis = [1 5 2 9];
data.notes = "This is just a trivial example for stackoverflow. I didn't check to see if it runs in matlab or not, my bad."
data.versions.current = "this one";
data.versions.previous = olddata;
The point is ANY matlab object/datatype/whatever you want to call it, can be referenced by a field in the struct. The last entry shows that we can even reference another struct in the field of a struct. The implication of this last bit is we could look at the date of creation of the previous verions:
data.versions.previous.date_created
To me this looks just like objects in java EXCEPT I haven't put any methods in there. Matlab does support java objects which to me look a lot like these structs, except some of the fields can reference functions.
Technically, it's a form of indexing, as per mwengler's answer. However, it can also be used for method invocation on objects in recent versions of MATLAB, i.e.
obj.methodCall;
However note that there is some inefficiency in that style - basically, the system has to first work out if you meant indexing into a field, and if not, then call the method. It's more efficient to do
methodCall(obj);

Constants in MATLAB

I've come into ownership of a bunch of MATLAB code and have noticed a bunch of "magic numbers" scattered about the code. Typically, I like to make those constants in languages like C, Ruby, PHP, etc. When Googling this problem, I found that the "official" way of having constants is to define functions that return the constant value. Seems kludgey, especially because MATLAB can be finicky when allowing more than one function per file.
Is this really the best option?
I'm tempted to use / make something like the C Preprocessor to do this for me. (I found that something called mpp was made by someone else in a similar predicament, but it looks abandoned. The code doesn't compile, and I'm not sure if it would meet my needs.)
Matlab has constants now. The newer (R2008a+) "classdef" style of Matlab OOP lets you define constant class properties. This is probably the best option if you don't require back-compatibility to old Matlabs. (Or, conversely, is a good reason to abandon back-compatibility.)
Define them in a class.
classdef MyConstants
properties (Constant = true)
SECONDS_PER_HOUR = 60*60;
DISTANCE_TO_MOON_KM = 384403;
end
end
Then reference them from any other code using dot-qualification.
>> disp(MyConstants.SECONDS_PER_HOUR)
3600
See the Matlab documentation for "Object-Oriented Programming" under "User Guide" for all the details.
There are a couple minor gotchas. If code accidentally tries to write to a constant, instead of getting an error, it will create a local struct that masks the constants class.
>> MyConstants.SECONDS_PER_HOUR
ans =
3600
>> MyConstants.SECONDS_PER_HOUR = 42
MyConstants =
SECONDS_PER_HOUR: 42
>> whos
Name Size Bytes Class Attributes
MyConstants 1x1 132 struct
ans 1x1 8 double
But the damage is local. And if you want to be thorough, you can protect against it by calling the MyConstants() constructor at the beginning of a function, which forces Matlab to parse it as a class name in that scope. (IMHO this is overkill, but it's there if you want it.)
function broken_constant_use
MyConstants(); % "import" to protect assignment
MyConstants.SECONDS_PER_HOUR = 42 % this bug is a syntax error now
The other gotcha is that classdef properties and methods, especially statics like this, are slow. On my machine, reading this constant is about 100x slower than calling a plain function (22 usec vs. 0.2 usec, see this question). If you're using a constant inside a loop, copy it to a local variable before entering the loop. If for some reason you must use direct access of constants, go with a plain function that returns the value.
For the sake of your sanity, stay away from the preprocessor stuff. Getting that to work inside the Matlab IDE and debugger (which are very useful) would require deep and terrible hacks.
I usually just define a variable with UPPER_CASE and place near the top of the file. But you have to take the responsibly of not changing its value.
Otherwise you can use MATLAB classes to define named constants.
MATLAB doesn't have an exact const equivalent. I recommend NOT using global for constants - for one thing, you need to make sure they are declared everywhere you want to use them. I would create a function that returns the value(s) you want. You might check out this blog post for some ideas.
You might some of these answers How do I create enumerated types in MATLAB? useful. But in short, no there is not a "one-line" way of specifying variables whose value shouldn't change after initial setting in MATLAB.
Any way you do it, it will still be somewhat of a kludge. In past projects, my approach to this was to define all the constants as global variables in one script file, invoke the script at the beginning of program execution to initialize the variables, and include "global MYCONST;" statements at the beginning of any function that needed to use MYCONST. Whether or not this approach is superior to the "official" way of defining a function to return a constant value is a matter of opinion that one could argue either way. Neither way is ideal.
My way of dealing with constants that I want to pass to other functions is to use a struct:
% Define constants
params.PI = 3.1416;
params.SQRT2 = 1.414;
% Call a function which needs one or more of the constants
myFunction( params );
It's not as clean as C header files, but it does the job and avoids MATLAB globals. If you wanted the constants all defined in a separate file (e.g., getConstants.m), that would also be easy:
params = getConstants();
Don't call a constant using myClass.myconst without creating an instance first! Unless speed is not an issue. I was under the impression that the first call to a constant property would create an instance and then all future calls would reference that instance, (Properties with Constant Values), but I no longer believe that to be the case. I created a very basic test function of the form:
tic;
for n = 1:N
a = myObj.field;
end
t = toc;
With classes defined like:
classdef TestObj
properties
field = 10;
end
end
or:
classdef TestHandleObj < handle
properties
field = 10;
end
end
or:
classdef TestConstant
properties (Constant)
field = 10;
end
end
For different cases of objects, handle-objects, nested objects etc (as well as assignment operations). Note that these were all scalars; I didn't investigate arrays, cells or chars. For N = 1,000,000 my results (for total elapsed time) were:
Access(s) Assign(s) Type of object/call
0.0034 0.0042 'myObj.field'
0.0033 0.0042 'myStruct.field'
0.0034 0.0033 'myVar' //Plain old workspace evaluation
0.0033 0.0042 'myNestedObj.obj.field'
0.1581 0.3066 'myHandleObj.field'
0.1694 0.3124 'myNestedHandleObj.handleObj.field'
29.2161 - 'TestConstant.const' //Call directly to class(supposed to be faster)
0.0034 - 'myTestConstant.const' //Create an instance of TestConstant
0.0051 0.0078 'TestObj > methods' //This calls get and set methods that loop internally
0.1574 0.3053 'TestHandleObj > methods' //get and set methods (internal loop)
I also created a Java class and ran a similar test:
12.18 17.53 'jObj.field > in matlab for loop'
0.0043 0.0039 'jObj.get and jObj.set loop N times internally'
The overhead in calling the Java object is high, but within the object, simple access and assign operations happen as fast as regular matlab objects. If you want reference behavior to boot, Java may be the way to go. I did not investigate object calls within nested functions, but I've seen some weird things. Also, the profiler is garbage when it comes to a lot of this stuff, which is why I switched to manually saving the times.
For reference, the Java class used:
public class JtestObj {
public double field = 10;
public double getMe() {
double N = 1000000;
double val = 0;
for (int i = 1; i < N; i++) {
val = this.field;
}
return val;
}
public void setMe(double val) {
double N = 1000000;
for (int i = 1; i < N; i++){
this.field = val;
}
}
}
On a related note, here's a link to a table of NIST constants: ascii table and a matlab function that returns a struct with those listed values: Matlab FileExchange
I use a script with simple constants in capitals and include teh script in other scripts tr=that beed them.
LEFT = 1;
DOWN = 2;
RIGHT = 3; etc.
I do not mind about these being not constant. If I write "LEFT=3" then I wupold be plain stupid and there is no cure against stupidity anyway, so I do not bother.
But I really hate the fact that this method clutters up my workspace with variables that I would never have to inspect. And I also do not like to use sothing like "turn(MyConstants.LEFT)" because this makes longer statements like a zillion chars wide, making my code unreadible.
What I would need is not a variable but a possibility to have real pre-compiler constants. That is: strings that are replaced by values just before executing the code. That is how it should be. A constant should not have to be a variable. It is only meant to make your code more readible and maintainable. MathWorks: PLEASE, PLEASE, PLEASE. It can't be that hard to implement this. . .