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.
Related
classdef Dog
end
d=Dog(); can size(d) be controlled? Is there some property to set or method to overload?
Ultimately I have like d.data = [1, 2, 3] and want length(d) == 3. I'm aware I can make d.length(). As an aside, is there a list of MATLAB "magic methods", i.e. functions that control interaction with classes, like subsref?
In MATLAB, don't think of class method as similar to class methods in other languages. Really, what they are is overloaded versions of a function.
size(d) is the same as d.size() (which is the same as d.size, parentheses are not needed to call a function), if d is an object of a custom class and size is overloaded for that class.
So, you can define function size in the methods section of your classdef, to overload size for your class. You can also create a size.m file within a #Dog/ directory to accomplish the same thing.
For example, if you create a file #char/size.m with a function definition inside, you will have overloaded size for char arrays.
The above is true for any function. Some functions, when overloaded, can cause headaches. For example be careful when overloading numel, as it could cause indexed assignment expressions to fail. size is used by the whos command to display variable information, as well as by the similar functionality in the GUI, so it is important to have it behave in the expected way.
The object behavior that you might want to change that is not obviously a function, relates to operators. Each operator is also defined by a function (including end in indexing!). See the docs for a full list.
I'd like to be able to view the structure of objects in Matlab/GNU Octave the same way as I do in R (using the str() function). Is there a function that does this? An example task would be returning nr rows and cols in matrix, but also all the arguments for a given function.
I'm aware that I could use both size() and help() (but not for function files) separately to get this information.
There are several useful functions for displaying some information about Matlab objects (I can't say anything about Octave compatibility), but I'm not sure they'll provide the same detail as R's str(). You can display all of the methods of a class with the methods function, e.g.:
methods('MException')
which returns
Methods for class MException:
addCause getReport ne throw
eq isequal rethrow throwAsCaller
Static methods:
last
The what function will return similar results. Or methods can be used on an object of a given class:
ME = MException('Test:test','Testing');
methods(ME)
Similarly, you can view the properties with properties and the events with events.
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).
Maybe it's a basic question but here I go. I would like to have a .m with all the functions that will be accessed by other scripts and functions.
I tried just doing a script with all the functions and call it in other functions code.
And I got and error. Could you please explain me how can I solve this?
I'm trying this, which gives me no error, and does what I want it to do, still, is it a good way to do it? Any suggestions?
function PruebasLlamaFuncion
funcionFEM=#PruebasTodasFunciones;
a=funcionFEM('OVERPOWER',1,5)
b=funcionFEM('POWEROVERWELMING',2)
end
...
function a=f(nombre,varargin)
f=str2func(nombre)
a=f(varargin{1:end});
end
function d=OVERPOWER(J,c)
d=J*c;
end
function e=POWEROVERWELMING(J)
e=J;
end
Function placement
Matlab, unlike a number of other languages, permits a single file to contain only one main function that is visible to the rest of the system. The main function is the first function. (Documentation)
Any functions that are defined after the main function body are called local functions. These functions each create their own separate workspace (scope) and can be called by one another and, of course, by the main function.
Any functions that are defined within the main function body are called nested functions. These functions have their own workspace but are also able to access and change the variables of their parent function under certain conditions. Nested functions at the same nesting level can call each other and local functions, but local functions cannot call nested functions since they are out of scope.
Workarounds
There are several options available to you depending on how you would like to proceed.
At the risk of giving too many options but desiring to be exhaustive, I'll put the list from what I would do first to what I would do last.
For most things, I would recommend 1 or 2.
The other options are more for creating libraries/APIs, but I included them to show what can be done.
Define Function1 and Function2 in separate m-files on the Matlab path or in the present working directory to call them normally.
Wrap the main body of your work (the one calling the functions) in a function itself and define the other functions as local functions or nested functions. Example:
function output = main(a,b,c)
Result=Function1(a,b,c);
Result2=Function2(b,d);
...
% You can define Function1 and Function2 here for nested functions
end
% Or you can define Function1 and Function2 here for local functions
You can get a bit more fancy and have a function that returns function handles (pointers) to the local or nested functions and then use the (in the example) struct to call the functions in another script:
function Functions = GetFunctions()
Functions.F1 = #(a,b,c) Function1(a,b,c);
Functions.F2 = #(a,b) Function2(a,b);
% You can define Function1 and Function2 here for nested functions
end
% Or you can define Function1 and Function2 here for local functions
If you have R2013b or above, you can do the same thing as above using the localfunctions function to create a cell array of handles to all local functions (in this case, the definitions are required to be outside the main function body).
function Functions = GetFunctions()
Functions = localfunctions(); % R2013b+ only
end
% Define Function1 and Function2 here for local functions
You can also create a class with static functions:
classdef Functions
methods(Static)
% Define Function1 and Function2 here and call them just like the struct above.
end
end
I hope that makes sense and hopefully helps.
I think you're misunderstanding something. A script is for calling a series of functions/other scripts in sequence. If you just want your functions to be accessible in other code, you only need to make sure they're on the path. You would never need a "script containing all the functions". You may be thinking of local functions, but these are the exact opposite of what you want (they can't be called from outside the function where they're defined or other local functions in the same file).
e.g. if Function1 and Function2 are on your path, you could write a script like this, perhaps as a demo for how to use those two functions:
a = 0;
b = 1;
c = 2;
d = 'Unicorns';
Result=Function1(a,b,c);
Result2=Function2(b,d);
It does not and should not have any function definitions in it. If your script can't find the functions, use addpath (see docs), to put the folder where these function files reside into your path. The m files should be given the same name, e.g. the following needs to go in a file called myfunc.m
function result = myfunc(a,b,c)
Functions in your working directory can also be called even if that directory isn't on your path.
Suppose I want to declare some variables then declare a function:
x = 2;
function y = function(x)
y = (x^2)+1;
end
y = function(x);
disp(y)
Matlab returns the error "Function keyword use is invalid here..."
Why can't I declare variables or write any text before declaring a function? Is there good reason or is it a quirk?
EDIT:
To clarify, I do know how to get around this problem (but thanks for the suggestions nonetheless) but I suppose I'm asking why the Matlab team made this decision. By making a function declaration the first line of a file, does it have implications for memory management, or something?
The REPL prompt of Scala can have a function defined after a variable. So this is a choice (a quirk if you want) from Matlab's inner internals.
If a function is defined in a file, there are two possibilities:
The main function of that file. Then the file must begin with the function declaration: in your example, function y = fun(x). I'm using fun as the function's name. I don't think function can be used as a function's name.
See here for more details.
A nested function. In this case, the function declaration and definition can be within another function of the preceding case.
See here for more details.
As you can see, in either case the file begins with a function declaration (namely that of the main function).
The function can also be defined as an anonymous function. Then no declaration is needed, and the function can be defined anywhere. But there's a restriction: the function can contain only a single statement (so it cannot define internal variables other than the output). Therefore this method can only be used for simple functions.
In your example, the function could be defined anonymously as fun = #(x) x^2+1.
See here for more details.
Others have given good info about nested functions and such.
But the reason for the error you get is that "function" is a reserved word in Matlab. You cannot have a function with this name.
function y = my_function(x)
y = (x^2)+1;
end
And stick it in another file called my_function.m