Create Custom Functions in MATLAB - matlab

I'm having problems with functions in matlab, I need to do an equalizer that uses 3 filter (high pass, low pass, band pass), I've created three diferent scripts to do this filters, now I want my main program of the equalizer call this 3 scripts, someone knows how to do this? I've serach in the internet but i don't found anything that can help me.

If I understand you correctly, you are wanting to pass the filters you have created in as functions to some script that will do the processing. This is fairly straightforward to do by passing in a function handle as an argument. If, for example, you have a function called high_pass_filter (written in a file high_pass_filter.m), then you can pass it in as an argument to a function using something like:
do_processing(#high_pass_filter, arguments);
In the function do_processing, it has as its definition something like
function do_processing(filter, arguments)
then to apply the filter (i.e. execute high_pass_filter.m), you just need to write
filter(arguments_for_filter_function);
Then you can call the same processing function for the three different filters.
More on function handles can be found on this page of the Matlab documentation

Related

Documenting MATLAB function overloading (variable arguments) so the usage popup is helpful

I'm writing MATLAB functions for use by others. I know how to use nargin, varargin, etc. to create a function with variable number of inputs.
The function I'm currently writing is recursive and I need to pass an argument to handle the recursion, but the user should never pass anything in for that argument (or they should pass in the non-intuitive starting value, but they don't need to be distracted by that). I want to 'hide' this argument from the user, so that when they're writing code to use this function and MATLAB pops up that little yellow window that tells them what arguments the function takes, it just prompts them for the arguments they care about.
To be more explicit, when you type rand(, MATLAB pops up a little help window with
rand()
rand(n)
rand(sz1,...,szN)
...
My function recursively builds a matrix and I've currently defined it this way:
function ret = M(arg1, arg2, HideThisRecursiveArgument)
% code that sets the starting value for HideThisRecursiveArgument when it's not passed
% code that calls M(...) again with a different recursion value
end
When the user types M(, I want MATLAB's little help popup to display the usage as:
M(arg1, arg2)
(arg1 and arg2 are named in a self descriptive manner, so this would be a sufficient 'help page' for my function.)
How can I document this usage so MATLAB's function usage help popup will display this to the user?
If I use varargin, the user might get distracted/confused by trying to figure out what else could be passed in, so that's unsatisfactory. I've tried defining my function with 2 arguments and then looking for a 3rd when it's called, but MATLAB doesn't like that.
Edit
I've found the Add Help for Your Program page, and if the user uses the help command or clicks the More Help... link in that yellow usage popup, I can control what they see there, but this doesn't tell me how to control what appears on the usage popup.
I would opt for two separate interfaces, the function to be called externally and your internal recursive function with the hidden argument:
function z=foo(x,y)
z=internalfoo(x,y,pi);
end
function z=internalfoo(x,y,secret)
if x>y
z=internalfoo(y,x,secret);
else
z=secret*x;
end
end
You can place both in the same file foo.m, only the foo() can be called externally (unless you do nasty stuff). Above example contains a local function. Depending on your task a nested function with shared variables is sometimes practical for recursion.
Regarding the second part of your question, look into functionSignatures.json. This allows you to customize the code suggestions and completions, unfortunately only within the Live Editor.
Examples incl. multiple signatures for the same function can be found in the doc.
Note: I had to restart MATLAB prior to experimenting in the Live Editor
Additionally, if you use R2021a checkout the new arguments syntax for declaring function argument validation, see doc.

Checking the functions that need to be used by a script in Matlab

I have a package of code that's been written by someone else. I am running a script, which calls some functions, which in turn calls some more functions, etc. I would like to get the list of functions that are not MATLAB built-in functions but are a part of the package.
I tried using matlab.codetools.requiredFilesAndProducts('file.m'), which gives me a list of such functions, but not all the functions. I can see when I look at the code that there are many more functions called by a function in the script. Does this command only show 'first-level' functions? How can I get the full list?
This function performs well, but isn't guaranteed to get all files. Works fine for me though
http://www.mathworks.com/matlabcentral/fileexchange/15484-recursively-get-file-dependencies-of-a-given-function/content/getFileDependencies.m
Check out the function inmem which may help to solve this task. It displays all matlab functions that are currently in memory. Thus it lists those functions that have been recently called, i.e. that have been called since the last clear allor clear functions statement. Thus you would start with a clean workspace, execute your program, and check with inmem which functions are loaded into the cache and are not in the matlab install directory, those are the functions you are interested in.
You may also use the command-line helper disp-inmem that was scripted to (half-)automate this task.

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.

hierarchy of functions in MatLab

I have been reading someone else's matlab code and I don't know how the code structured. I mean I would like to know the hierarchy of functions, which function uses which function. I am reading the code to figure that out but its taking a lot of time.
So is there any other way I can see this hierarchy without reading the whole thing? To be honest it is starting to get confusing. Maybe MatLab has a built in function for that! I found this:
How can I generate a list of function dependencies in MATLAB?
but this doesn't seem to be helpful!
The MATLAB profiler will show you what functions are called by your code (and much more information to boot) and allow you to click through the hierarchy of function calls. You can either call profile on and then run your code, then call profile off and profile viewer, or you can simply call profile viewer and type a single line of code to run in the edit box at the top.
Use the dependency report provided in MATLAB:
http://www.mathworks.co.uk/help/matlab/matlab_prog/identify-dependencies.html
There are also some tools on the File Exchange, such as fdep.
No idea about a function to show visible or depended-upon functions. However the basic rules are:
1) Only the first function in a .m file (normally has to have the same name as the file itself) is visible outside that file.
2) Any function can see any top level (see 1.) function if the file is in the matlab path. Matlab can show you the path so you know where it's hunting.
3) The order of the path is important, the first instance of a function called foo found in the path will be called. Obviously the current directory is at the top of the path.
3) All functions in a given file can see all other functions in that file.
That's the basics. No doubt there are other rules, and possibly exceptions to this. But that understanding generally serves me well.
Obviously the easiest way to work out which function is being called is to click on it in the editor and open it.
One thing I do is simply place in each function at the beginning fprintf("inside function <name>/n"); and at the end of the function fprintf("leaving function <name>/n"); where <name> is the name of the function.
This will give you a very specific list of which function is being called by which function (based on the order that they appear). Another thing like this would be to place fprintf("function <name1> calling function <name2>/n"); so you can be more explicit about which function is being called by which one.

Pass variable from GUI to function in MATLAB

I have a MATLAB GUI that loads to aid in visually pre-processing data. Essentially it prompts the user to adjust the data range, reduce number of data points, etc... all while providing an updated graph. Upon completion of this work, I want to be able to close out the GUI and pass variables from the GUI to another MATLAB function that does the data analysis. I have found lots of information on how to pass information from a function TO and GUI, but not the other way around.
Any help would be greatly appreciated.
Global variables can cause hard to find bugs. The best solution for your problem (where you want to pass the data directly to another function on close) might be to call the analysis function from the Figure Close Request Function. When the figure your GUI is running in is told to close, it will run the code in this function, which can call your analysis function and have access to the GUI's data.
Matlab GUIs are functions: the code exists in a .m file just like other functions. Like regular functions, they can have return values. You can get as fancy as you want messing with the varargout system, or you can simply return a value, structure, or cell array containing whatever you want. Open up the m-file and edit it to return what you want it to.
Note: If you require special processing when the figure is being closed to generate the appropriate return value, you can reimplement the closeRequestFcn as you see fit.
The easy way: you declare as global variable, where variable stores the data that you want to carry from the GUI to the main MATLAB workspace. Then, you also declare the same global variable on the command window. Hereinafter, variable to be accesible from both scopes, the GUI and the main workspace.
You could also use save or any other alternatives as csvwrite or dlmwrite to store the data into a file, but this doesn't seem to be your case.