a handle to shorten the name of stuct/class in matlab - matlab

I have a struct with relative sophisticated data trees. for example:
class.data.head{1}.data2
What I wish to get is a variable named data2_link to link with address class.data.head{1}.data2, so that:
(1) if there is any change on class.data.head{1}.data2, it will automatically reflected to data2_link as well, and vise versa.
(2) I do not have to type the long name to access the data at class.data.head{1}.data2.
Thanks!

Matlab does not support references. The only exception is handle which allows references to objects.
To use it, data2 must be an object with superclass handle, then you could simply write:
data2_link=class.data.head{1}.data2
Note that object oriented matlab significantly slows down your code unless you use Matlab 2015b or newer.

There is an extremely discouraged way to do it. you can create a function handle that evaluates the desired expression:
data2_link = #() evalin('caller', 'class.data.head{1}.data2')
Now every time you need that expression just call it using
>> data2_link()
The extra parentheses are necessary to invoke the function defined by function handle.

Just got another idea, you could use subsref to access it and subassign to write. It is not really what I would call a reference because you still need S, but it probably comes as close to it as possible without using OOP.
S=substruct('.','data','.','head','{}',{1},'.','data2')
%previous line is the same as: S=struct('type',{'.','.','{}','.'},'subs',{'data','head',{1},'data2'})
f=subsref(class,S)

Related

Collect internal variables of nested functions in matlab

I have a project consisting of multiple nested functions.
For debugging purpose I want to save all internal variables in one way or another, in order to display figures, replay parts of code etc...
I also want to keep this as transparent as possible regarding calculation time.
My first thought was to create a global variable, and store programmatically at the end of each function the inputs and outputs inside the variable as a structure :
globalVariable.nameOfParentfunction_NameOfFunction.nameInput1 = valueInput1;
globalVariable.nameOfParentfunction_NameOfFunction.nameInput2 = valueInput2;
...
globalVariable.nameOfParentfunction_NameOfFunction.nameOutput1 = valueOutput1;
...
Is it possible to use some kind of reflection to get the name and value of inputs/outputs without necessarily parse the file where the function is written?
I found a good but maybe outdated topic about parsing
How do I collect internal signals?
The simple solution is to use save, which will save all variables in the current workspace (the function’s context) to file.
If you want to keep the values in memory, not in a file, you can use names = who to get a list of all variables defined in the current workspace, then use val = eval(names{i}) to get the value of the variable called name{i}.
I would recommend putting all of that in a separate function, which you can call from any other function to store its variables, to avoid repeating code. This function would use evalin('caller',…) to get names and values of variables in the workspace of the calling function.
Note that using eval or evalin prevents MATLAB from optimizing code using its JIT. They also are dangerous to use, since they can execute arbitrary code, however in this case you control what is being executed so that is no a concern.

Exploit Matlab copy-on-write by ensuring function arguments are read-only?

Background
I'm planning to create a large number of Matlab table objects once, so that I can quickly refer to their contents repeatedly. My understanding is that each table variable/column is treated in copy-on-write manner. That is, if a table column is not modified by a function, then a new copy is not created.
From what I recall of C++ as of 1.5 decades ago, I could ensure that the code for a function does not modify its argument's data by using constant-correctness formalism.
The specific question
I am not using C++ in these days, but I would like to achieve a similar effect of ensuring that the code for my Matlab function doesn't change the data for selected arguments, either inadvertently or otherwise. Does anyone know of a nonburensome way to do this, or just as importantly, whether this is an unrealistic expectation?
I am using R2015b.
P.S. I've web searched and came across various relevant articles, e.g.:
http://www.mathworks.com/matlabcentral/answers/359410-is-it-possible-to-avoid-copy-on-write-behavior-in-functions-yet
http://blogs.mathworks.com/loren/2007/03/22/in-place-operations-on-data
(which I need clarification on to fully understand, but it isn't my priority just now)
However, I don't believe that I am prematurely optimizing. I know that I don't want to modify the tables. I just need a way to enforce that without having to go through contortions like creating a wrapper class.
I've posted this at:
* Stack Overflow
* Google groups
There is no way of making variables constants in MATLAB, except by creating a class with a constant (and static?) member variable. But even then you can do:
t = const_table_class.table;
t(1,1) = 0; % Created and modified a copy!
The reason that a function does not need to mark its inputs as const is because arguments are always passed by value. So a local modification does not modify data in the caller’s workspace. const is something that just doesn’t exist in the MATLAB language.
On the other hand, you can be certain that your data will not be modified by any of the functions you call. Thus, as long as the function that owns the tables does not modify them, they will remain constant. Any function you pass these tables to, if they attempt to modify them, they will create a local copy to be modified. This is only locally a problem. The memory used up by this copy will be freed upon function exit. It will be a bug in the function, but not affect code outside this function.
You can define a handle class that contains a table as it's preperty. Define a property set listener that triggers and generates error/warning when the value of the property changes.
classdef WarningTable < handle
properties (SetObservable)
t
end
methods
function obj = WarningTable(varargin)
obj.t = table(varargin);
addlistener(obj,'t','PreSet',...
#(a,b)warning('table changed!'));
end
end
end
This should generate warning:
mytable = WarningTable;
mytable.t(1,1) = 0;

Call overloaded function from specific toolbox in MATLAB

I have some Matlab-Toolboxes installed. In my Matlab version one of the Toolbox-Functions collides with another. In this case it is hessian. I want to use the hessian function of the symbolic-Toolbox.
When in C/C++ Functions are multiple defined like the function for cos and I still want to use the “standard” cos-function I can write:
std::cos(x);
Is there something similar in matlab?
If you have overloaded methods and want to call the built in one, you can use the function builtin. From the official documentation:
builtin(function,x1,...,xn) executes the built-in function with the
input arguments x1 through xn. Use builtin to execute the original
built-in from within a method that overloads the function. To work
properly, you must never overload builtin.
The syntax for using it is:
[y1,...,yn] = builtin(function,x1,...,xn)
Friendly advice: If you want to try overloading builtin ("hmm, I wonder what would happen"), remember to save stuff first.
In a very similar way that you were describing for c/c++, you can use a specific toolbox function by adding the name of the toolbox first : ToolboxName\function2call()
First use the which command to make sure of which function from which toolbox will be loaded with a specific call syntax.
Since I do not have the toolbox you are mentioning i'll use the classic fopen function as an example.
The first fopen function called without any other parameter will be the built in function which is used to return a handle to a file. Indeed, the which command confirms that:
>> which fopen
built-in (C:\TLAB13a\toolbox\matlab\iofun\fopen)
Now let's say I want to use the fopen function to open a serial port, I need to prefix the call to fopen with the name of the toolbox/object, like so: serial\fopen. Let's first make sure this way of calling point to the right function:
>> which serial\fopen
C:\TLAB13a\toolbox\matlab\iofun\#serial\fopen.m % serial method
Bingo !
And just to make sure this works when you are calling these functions, let's call them for real (with dummy parameters):
>> fopen('toto')
ans =
-1
>> serial\fopen('toto')
Error using serial (line 72)
The PORT must be specified.
It worked. The first simple call to fopen('toto') return -1 because it couldn't find a file named "toto".
The second call to serial\fopen('toto') errored because the serial port was not defined, but the right function was called.
Edit:
You can also override the order in which Matlab will fetch functions by re-ordering the Matlab path. If you put the symbolic toolbox before the other one in your path, then when called without explicit information, Matlab will execute the first function it finds in the path.
I would still recommend the first solution with explicit declaration though, because changing the path order could mess up other function call in case you have many overloaded functions.

Good way to pass many variables to function?

When one has a function, which needs many specific variables when called, what is a good way, to pass them?
Should one always pass all variable explicitly? How about storing them in structs (or objects)? But somehow I think, this makes things a bit obscure, as these structs/objects have to be well defined to make sure, they have all the fields, when handed in to the function in question.
Also probably local variables are accessed most quickly, whereas adressing struct fields might be slow in a loop...
Or is it a good thing to run an external script where everything is defined global (but even in this case on has to make everything available to the function using the global keyword)
A good way to pass many variables to a function, is to use varargin. Use it together with nargin.
function varlist2(X,Y,varargin)
fprintf('Total number of inputs = %d\n',nargin);
nVarargs = length(varargin);
fprintf('Inputs in varargin(%d):\n',nVarargs)
for k = 1:nVarargs
fprintf(' %d\n', varargin{k})
end
Varargin can also be used for optional variables.. So it gives a lot of options...

Find indirect calls to specific built-in MATLAB function

What do I want?
I am looking for a way to detect all points in my code where a specific function is called.
Why do I want it?
Some examples:
Some output comes out sorted or randomized, and I want to know where this happens
I am considering to change/overload a function and want to know in which part of my code this could have impact
What have I tried?
I tried placing a breakpoint in the file that was called. This only works for non builtin functions which are called from short running code that always executes everything.
I tried 'find files', this way I can easily find direct calls to sort but it is not so easy to find a call to sort invoked by unique for example.
I have tried depfun, it tells me:
whether something will be called
from where non-builtin functions will be called
I thought of overloading the builtin function, but feels like a last resort for me as I am afraid to make a mess. | Edit: Also it probably won't help due to function precedence.
The question
What is the best way to track all potential (in)direct function calls from a specific function to a specific (built-in)function.
I don't exactly understand your use case, but I guess most of the information you want can be obtained using dbstack, which gives you the call-stack of all the parent functions calling a certain function. I think the easiest way is to overload built-in functions something like this (I tried to overload min):
function varargout = min(varargin)
% print info before function call
disp('Wrapped function called with inputs:')
disp(varargin)
[stack,I] = dbstack();
disp('Call stack:')
for i=1:length(stack)
fprintf('level %i: called from line %i in file %s\n', ...
i, stack(i).line, stack(i).file);
end
% call original function
[varargout{1:nargout}] = builtin('min', varargin{:});
% print info after function call
disp('Result of wrapped function:')
disp(varargout)
I tried to test this, but I could not make it work unfortunately, matlab keeps on using the original function, even after playing a lot with addpath. Not sure what I did wrong there, but I hope this gets you started ...
Built-in functions take precedence over functions in local folder or in path. There are two ways you can overload a built-in for direct calls from your own code. By putting your function in a private folder under the same directory where your other MATLAB functions are. This is easier if you are not already using private folder. You can rename your private folder once you are done investigating.
Another way is to use packages and importing them. You put all your override functions in a folder (e.g. +do_not_use). Then in the function where you suspect built-in calls are made add the line "import do_not_use.*;". This will make calls go to the functions in +do_not_use directory first. Once you are done checking you can use "clear import" to clear all imports. This is not easy to use if you have too many functions and do not know in which function you need to add import.
In addition to this, for each of the function you need to follow Bas Swinckels answer for the function body.
Function precedence order.
Those two methods does not work for indirect calls which are not from your own code. For indirect calls I can only think of one way where you create your own class based on built-in type. For example, if you work only on double precision types, you need to create your own class which inherits from double and override the methods you want to detect. Then pass this class as input to your code. Your code should work fine (assuming you are not using class(x) to decide code paths) since the new class should behave like a double data type. This option will not work if your output data is not created from your input data. See subclassing built-in types.
Did you try depfun?
The doc shows results similar to the ones you request.
doc depfun:
...
[list, builtins, classes, prob_files, prob_sym, eval_strings, called_from, java_classes] = depfun('fun') creates additional cell arrays or structure arrays containing information about any problems with the depfun search and about where the functions in list are invoked. The additional outputs are ...
Looks to me you could just filter the results for your function.
Though need to warn you - usually it takes forever to analyze code.