How to see the type of a matlab variable - matlab

I'm looking at a rather large and poorly written Matlab program. One of the things that makes understanding the code tricky is the variables don't show their type. In searching I only found explanations how to do this while debugging code(the whos and class commands). I'm looking for a way to view type information in the editor itself.
For example in the following code I would like to know the type of A and B:
classdef Data
properties
B;
function obj = Data(A)
obj.B = A.B;
end
Or is the type not determined until the function is called, and A could be any class with a B parameter?

As I mentioned in the comments, unfortunately there isn't any way I know of to do this in the IDE without entering the debugger because MATLAB is not statically typed. You can also trace through the function and see what is calling the methods/functions/etc. in question and the variables used.
Your ending sentence is correct. Looking at your example solely in the eyes of the IDE A could be any data type, even one where the dot notation isn't valid (and thus would throw an error). It's up to the user to add input validation for functions that are not built in.

Usually numeric variables are defined as doubles, you can ask if a variable belongs or not to a specific data type, here are some ways to do it.

Related

`mlx` interface for Java packaging of Matlab functions?

I am looking at the Matlab information on packaging functions for invocation from Java, specifically in the context of a variable number of input arguments. A number of function signatures are for "mlx interface", but there is no explanation of what this means.
Web searching shows that *.mlx is file extension of Jupyter-like file for Matlab code. It is unclear whether this has anything to do with the use of this acronym in the interface documentation cited above. The manner in which it is presented seems to indicate that any reader should know what it is, and mlx signatures take up half of the examples shown, so it is obviously a prominent use case. In contrast, I've never heard of a Jupyter-like Matlab file before, and likewise, did not know of an *.mlx file extension until now (though there are many TMW corners I've not ventured near).
What does "mlx interface" mean in the context of function signatures in Java packaged Matlab?
Why does it figure so prominently into the Java interface?
It looks as if the answer is not available in Matlab's doc documentation,
nor the HTML counterparts on the web. Hints of the answer are buried deep
in real-book documenation like MATLAB Compiler SDK Java User's Guide:
A standard signature in Java...specifies input arguments for each
overloaded method as one or more input arguments of class
java.lang.Object or any subclass (including subclasses of
MWArray). The standard interface specifies return values, if any,
as a subclass of MWArray.
[The] mlx API...allows the user to specify the inputs to a
function as an Object array, where each array element is one input
argument. Similarly, the user also gives the mlx interface a
preallocated Object array to hold the outputs of the function. The
allocated length of the output array determines the number of
desired function outputs.
The mlx interface may also be accessed using java.util.List
containers in place of Object arrays for the inputs and outputs.
Note that if List containers are used, the output List passed in
must contain a number of elements equal to the desired number of
function outputs.
A web search for mlx-api shows that it is Matlab interface for
C/C++: Functions Generated from MATLAB Files.
While the acronym mlx may have been motivated by this, it seems that
the only thing inheritted by the Java signature is the acronym. The
signature itself is completely dissimilar to that in the posted page
Pass Variable Numbers of
Inputs.

How to force Matlab/Simulink Coder to use the parameters created in simulink

I have a simulink model using matlab function blocks.
When i try to generate the C code from my model, the structures parameter scopes i used to represent my data are unused :
When i say unused i mean,
matlab coder creates a header file with all my structures defined.
but in the actual algorithms, when the structure should be sent as argument to a function, matlab coder just defines new variables for each of the fields of which values are hardcoded.
So something like : Function(parameter); with parameter contraining X = 5 and Y = 8 becomes Function(5,8); once generated (so the function definition creating new variables for each of the fields).
You can imagine how messy that gets once the structures get too big.
A friend of mine told me objects dont work with matlab coder. So replacing my structs with objects is not an option unless my friend was wrong.
Does anyone know how i could force matlab coder to actually use the structures i defined for him?
Or maybe there is another solution that i did not think of?
Thanks!
I have found the answer to my own question.
In the configuration file of the code generation, under "Optimization" tab, change "default parameter behaviour" from 'inlined' to 'tunable'.
I hope this will help others :)

Why Matlab Coder is slow?

I'm trying to build a Mex function in Matlab-r2015a using Matlab Coder. The entry point function I want to convert is alg.m which is called by main.m.
Following the procedure, I'm at the step in which I'm asked to "define the type of each input for every entry point function". I choose the automatic procedure and enter main.m
My problem is: in order to define the type of each input, the Matlab Coder takes a very long time; the same problem appears at the next step, when I have to check whether there are issues in the Matlab code. Is that because Matlab has to execute the whole main.m+alg.m?
I suspect this should be the case because when I impose values of parameters that make the computation faster, the input types and issue checks are done immediately. Anyway, I would like to have some more explanations and, if any, suggestions to solve the problem.
You are correct, both steps Define Input Types and Check for Run-Time Issues run main.m which will in turn run alg.m.
If the input data types for the entry-point function don’t change, two test-benches (namely two versions of your main.m) can be written – a shorter one that invokes the entry-point once for defining input types, and a more comprehensive one that thoroughly exercises alg.m. The former can be used to quickly define input types, and the latter should be used when checking for run-time issues.

Why "too many output arguments" when defining MATLAB containers.Map subclass method with 0 outputs?

I am trying to extend the MATLAB containers.Map class by subclassing it and adding an additional method with 0 outputs, but I encounter the "too many output arguments" error when executing the method. This is not specific to the new method implementation--any additional method that extends containers.Map() with 0 outputs will generate this error.
Specifically, the error is encountered when executing,
obj = Containers();
obj.testfun();
For the following class definition,
classdef Containers < handle & containers.Map
methods
% Test function to display keys.
function testfun(obj)
obj.keys(); % dumby thing to execute with incoming object.
disp('it works!');
end
end
end
However, if we slightly modify it to output at least one argument,
classdef Containers < handle & containers.Map
methods
% Test function to display keys.
function dumby = testfun(obj)
obj.keys();
disp('it works!')
dumby = 1;
end
end
end
It will execute correctly. The error appears to happen specifically when subclassing containers.Map. If it matters, I am using MATLAB R2014b. Any suggestions as to how to resolve this issue?
Don't try to subclass containers.Map. This is just my opinion, but MathWorks should have made it Sealed so that you just couldn't.
What's going on here is that when you type a.b, or a(b) or a{b}, that is translated into a call to the method subsref. All objects have that method. See doc subsref for more detail on exactly how MATLAB calls subsref but be warned - it's quite complicated.
Now if you want to customize the behaviour of your class, you can overload subsref by providing your own implementation. containers.Map does this, as it needs to support indexing by keys, which is not typical for other MATLAB classes.
I can't tell you precisely how subsref for containers.Map is implemented, as it's a built-in class so I can't see the code. But I'm guessing, from the behaviour you're seeing here, that at some point it's trying to work out whether .testfun() is a call to a method testfun, or a property testfun, or a field testfun, or something else, and one of the things it's doing is to see whether it is being called with output arguments and changing its behaviour accordingly.
This is a great example of where you're not really able to subclass the object without knowing (and possibly modifying) its internals, which is why I suggest that MathWorks might better have made this Sealed to prevent you from trying. In any case, you're not going to be able to subclass it with the behaviour you want, without a few workarounds (i.e. implementing your own overloaded subsref for your Containers class in order to make it work how you want) and a bit of reverse-engineering (i.e. second-guessing the internals of the subsref method of containers.Map).
Instead, you might try using an Adapter pattern, by creating your own class with a containers.Map as a private (maybe hidden) property, then implementing methods and properties that just pass through their arguments and outputs to the underlying containers.Map. Finally, implement your own methods as well.

"relative global" variables in matlab or other languages

I do scientific image processing in MATLAB, which requires solving weird optimization problems with many parameters that are used by an "experiment" function which has many different "helper functions" that use various subsets of the parameters. Passing these parameters around is a pain and I would like an elegant extensible solution.
My preferred solution would be a "relative global" variable - common to a "main" function's workspace, as well as any subfunctions that the main function calls and that specify they want to share that variable. But the relative global variable would not exist outside the function which declares it, and would disappear once the main function returns.
The code would look like this, except there would be many more experiment_helpers, each using the parameters in different ways:
function y = experiment(p1,p2,p3,...)
% declare relative global variables.
% these will not change value within this experiment function,
% but this experiment will be reused several times in the calling function,
% each time with different parameter values.
relative global p1, p2, p3 ...
% load and process some data based on parameters
...
% call the helper + return
y = experiment_helper(y,z);
end
function y = experiment_helper(y,z)
relative global p1, p3
%% do some stuff with y, z, possibly using p1 and p3, but not changing either of them.
...
end
I realize that you can get the desired behavior in several other ways -- you could pass the parameters to the sub-functions called by the experiment, you could put the parameters in a parameter structure and pass them to the sub-functions, and so on. The first is horrible because I have to change all the subfunctions' arguments every time I want to change the use of parameters. The second is okay, but I have to include the structure prefix every time I want to use the variables.
I suppose the "proper" solution to my problem is to use options structures much like matlab does in its own optimization code. I just wonder if there isn't a slicker way that doesn't involve me typing "paramStruct.value" every time I want to use the parameter "value".
I realize that relative global variables could cause all sorts of debugging nightmares, but I don't think they would necessarily be worse than the ones caused by existing global variables. And they would at least have more locality than unqualified globals.
So how does a real programmer handle this problem? Is there an elegant, easy to create and maintain design for this kind of problem? Can it be done in matlab? If not, how would you do it in another language? (I always feel guilty about using matlab as it doesn't exactly encourage good design. I always want to switch to python but can't justify relearning things and migrating the code base -- unless it would make me a much faster and better programmer within a few weeks, and the matlab-specific tools, such as wavelet and optimization toolboxes, could quickly+easily be found or duplicated within python.)
No, I don't think Matlab has exactly what you are looking for.
The best answer depends on if your primary concern is due to the amount of typing required to pass the parameters around, or if you are concerned about memory usage as you pass around large datasets. There are a few approaches that I have taken, and they all have pros and cons.
Parameters in a structure. You've already mentioned this, in your question,but I would like to reinforce it as an excellent answer in most circumstances. Instead of calling my parameter structure paramStruct, I usually just call it p. It is always locally scoped to the function I'm using, and then I need to type p.value instead of value. I believe the extra two characters are well worth the ability to easily pass around the complete set of parameters.
InputParser. I use the InputParser class a lot when designing functions which require a lot of inputs. This actually fits in well with (1), in that a sturcture of parameters can be passed in, or you can use 'param'/value pairs, and yuo can allow your function to define defaults. Very useful.
Nested functions can help in limited cases, but only when all of your functions can be defined hierarchically. It limits code re-use if one of your inner function can be generic enough to support multiple parent functions.
Pass by reference using handle classes. If your concern is memory. the new form of
classes actually allows you to define a paraemter structure which is passes by reference. The code looks something like this:
classdef paramStructure < handle
properties (SetAccess = public, GetAccess = public)
param1 = [];
param2 = [];
% ...
param100 = [];
end
end
Then you can create a new pass-by-reference structure like this
p = paramStructure;
And set values
p.param1 = randn(100,1);
As this is passed around, all passing is by reference, with the pros (less memory use, enables some coding styles) and cons (generally easier to make some kinds of mistakes.
global variables. I try really hard to avoid these, but they are an option.
What you're describing is exactly available in MATLAB using nested functions. They have their own workspace, but they also have access to the workspace of the parent function in which they are nested. So the parent function can define your parameters, and the nested functions will be able to see them as they have a shared scope.
It's a pretty elegant way of programming, and causes many fewer problems with debugging than globals. Recent versions of MATLAB even highlight shared variables in the editor in light blue, to help with this.