Is there a way to do command aliasing in matlab R2011b? - matlab

I am relatively new at Matlab.
I am trying to create an alias for a command that looks like the following.
run('full/path/to/some/script').
In particular, I would like to be able to write something equivalent to Bash's
alias myAlias = run('full/path/to/some/script')
And then be able to type myAlias and get the same effect as the right hand side.
I have looked at the documentation here, but I still get the error Undefined function or variable 'alias' when I try to use it, even after I first type syms at the prompt, so I believe that either I am not importing the toolbox correctly or this is not a feature in R2011b.
One additional requirement is that I would like the alias to stick even after I call clear, which should clear all the other active variables in the workspace.

for example:
f = #() run('foldername\scriptname')
then just writing f() will execute scriptname.
Here I've used an anonymous function, you can add more content to it if needed.

You can make #natan's answer tolerate clearing the workspace by making it an m-file.
In myAlias.m, put run('full/path/to/some/script'). I'm sure you are aware of this solution, but you might not want to do so, because of the resulting messy file system.
You can simply add the m-file to some folder and use addpath('where/ever/you/put/the/script') to make it accessible.

Related

How to show code from a script in a publish?

I want to publish my assignment with matlab.
At the start of the program, I want to print the code of my scripts to show the teacher what my functions do.
How can I do this?
So far the best way I do this is by making a dummy call at the start without ending the function call with ";"
However I'd really like to just print the code at the start.
You can use the type command:
type fileName.m
This will print the code, similarly to creating a variable and not using a semicolon to see the value of that variable.
There are tools in MATLAB for publishing code. You could conceivably even write a report in MATLAB code and publish that! Take a look at publishing MATLAB code and the documentation of the function publish
If you are interested to print particular lines from a .m file, look into dbtype.
Illustration from Mathworks site linked above. This:
becomes this:

Overwrote built in function - Standard deviation

I want to have a std.m file for the standard deviation. It is in data fun toolbox, but, by mistake, I changed the code and the std command is not working anymore. How can I run the original std (standard deviation) command?
Taking all the comments out, the function std.m is actually extremely simple:
function y = std(varargin)
y = sqrt(var(varargin{:}));
This is the definition of the standard deviation: the square root of the Variance.
Set built-in functions to Read-Only
Now don't go breaking the var.m file because it is more complex and I wonder if there would be copyright issue to display the listing here.
To avoid the problem of breaking built-in files, it is advisable to set all your Matlab toolbox files as Read Only. I remember old Matlab installer giving the option to do that at install time. I don't know if the installer still offers the option, but if not it is extremely easy to do it manually (on Windows, just select your folders, right-click Properties, tick read only and accept to propagate the property to all subfolders and files).
Overloading
Once this is done, your built-in files are safe. You can still modify the default behavior of a built-in function by overloading it. This consist in writing a function with the same name and arrange for it to be called before the default function (your overload function becomes the default one).
This article explain how to overload user functions.
Matlab does not recommend to directly overload the built-in functions (rather call it another name like mySTD.m for example), but if you insist it is perfectly feasible and still a much better option than modifying the built-in function... at least the original function is still intact somewhere.

At which lines in my MATLAB code a variable is accessed?

I am defining a variable in the beginning of my source code in MATLAB. Now I would like to know at which lines this variable effects something. In other words, I would like to see all lines in which that variable is read out. This wish does not only include all accesses in the current function, but also possible accesses in sub-functions that use this variable as an input argument. In this way, I can see in a quick way where my change of this variable takes any influence.
Is there any possibility to do so in MATLAB? A graphical marking of the corresponding lines would be nice but a command line output might be even more practical.
You may always use "Find Files" to search for a certain keyword or expression. In my R2012a/Windows version is in Edit > Find Files..., with the keyboard shortcut [CTRL] + [SHIFT] + [F].
The result will be a list of lines where the searched string is found, in all the files found in the specified folder. Please check out the options in the search dialog for more details and flexibility.
Later edit: thanks to #zinjaai, I noticed that #tc88 required that this tool should track the effect of the name of the variable inside the functions/subfunctions. I think this is:
very difficult to achieve. The problem of running trough all the possible values and branching on every possible conditional expression is... well is hard. I think is halting-problem-hard.
in 90% of the case the assumption that the output of a function is influenced by the input is true. But the input and the output are part of the same statement (assigning the result of a function) so looking for where the variable is used as argument should suffice to identify what output variables are affected..
There are perverse cases where functions will alter arguments that are handle-type (because the argument is not copied, but referenced). This side-effect will break the assumption 2, and is one of the main reasons why 1. Outlining the cases when these side effects take place is again, hard, and is better to assume that all of them are modified.
Some other cases are inherently undecidable, because they don't depend on the computer states, but on the state of the "outside world". Example: suppose one calls uigetfile. The function returns a char type when the user selects a file, and a double type for the case when the user chooses not to select a file. Obviously the two cases will be treated differently. How could you know which variables are created/modified before the user deciding?
In conclusion: I think that human intuition, plus the MATLAB Debugger (for run time), and the Find Files (for quick search where a variable is used) and depfun (for quick identification of function dependence) is way cheaper. But I would like to be wrong. :-)

How to remove the variable "clear" in MATLAB

Let's say you are some new programmer and you do something like...
%...la da da
%...programming away
if such && such
clear = 1;
else
clear = 0;
end
or in some other way, you assign the variable clear a value.
Is there some way to "clear" clear?
clearvars doesn't work. Clicking the workspace variable and manually clicking delete does work, but I think it's cheating.
This will do it:
builtin('clear','clear')
Note: Keep in mind to avoid such operations to keep code clarity. Only do overwrite when it is the exact action you want to take place. Otherwise it may cause future bugs if you forgot (or if another person uses your code and didn't realize it) that you have the clear (or any other) function overwritten. You could easily name this variable as doClear for example.
Any name, even builtin and feval can be overriden. In such case, you can use function handles instead to force MALTAB into interpreting a statement as a function call:
clear = str2func('clear');
clear('clear')
Obviously, str2func can also be overrriden! :) however, there exists a similar solution (inspired by Loren's article), which is creating a separate m-file that does the same thing:
function clearclear()
assignin('caller', 'clear', #clear);
Calling this function in the main workspace should allow you to do clear('clear') safely.
The second solution takes advantage of the fact that the m-file doesn't "see" the variable clear in the main workspace, and therefore can access the actual handle of the clear function properly.
A non intuitive way is
clear = rand(1000,500,700);
pack
This produces the following warning:
Warning: Variable 'clear' cannot be saved to a MAT-file whose version
is older than 7.3. To save this variable, use the -v7.3 switch.
Skipping...
It also suffers from the same issue that you can assign pack to be a variable.
Interesting problem! I found it surprisingly hard to find an ways to do this programatically (besides the one suggested by #TryHard)
Here is the I have come up with though it is a bit more powerfull than clear:
!matlab &
exit
Note that if you want to type this in the command line at once, you need to use a shift+enter in between.

Avoid MATLAB startup warning when overloading buildin functions?

As described here, I created my own figure.m which nicely overloads the built-in figure command. Now, whenever I start MATLAB I get the warning
Warning: Function C:\somepath\figure.m has
the same name as a MATLAB builtin. We
suggest you rename the function to
avoid a potential name conflict.
Is there any way to deactivate this warning, given that it is desired behavior in my case?
You might say that I should call my function differently instead of overloading, but I do feel for my development system this overloading is the right way to go...
Update
As mentioned by Aabaz you can globally turn off this warning using
warning off MATLAB:dispatcher:nameConflict
which needs to go at the beginning of matlabrc.m (before the path is set). However, I would still be interested in a solution which could specificially remove this error message for overloading figure.m (or some self-defined list of functions) instead of for all functions. I guess I'm asking a bit too much here ;-) ?
I cannot seem to replicate this warning with my Matlab version (R2008b) but anyway If you did not already try it you should look into the functions lastwarn and warning that allow you to identify and turn off this warning.
PS: the warning eventually came for some reason and I was able to use lastwarn and warning to turn it off.
>>[msgstr msgid]=lastwarn;
>>disp(msgid);
MATLAB:dispatcher:nameConflict
>>warning('off',msgid);
I should add that you should turn it off at startup for this to be effective between different sessions of Matlab.
I just ran into this problem on MATLAB R2014b where I also wanted to override figure. I think this is the closest solution to your updated question (3.5 years later...).
I think using the "dirty" trick from your comment is actually the cleanest, if done smartly as it doesn't require you to change matlabrc.m and can suppress the warning for only functions that you want to override built-in ones.
Put all your default overrides in a folder that is not on your permanent MATLAB path. I keep mine in ~/Documents/MATLAB/overrides on my Mac. I have e.g. ~/Documents/MATLAB/overrides/figure.m
Use startup.m to add overrides to your path with the warning turned off, and then turn it back on:
warning off MATLAB:dispatcher:nameConflict
addpath('/Users/victor/Documents/MATLAB/overrides');
warning on MATLAB:dispatcher:nameConflict
Not sure if tilde expansion works with addpath so I write the full path out.
Doing it this way suppresses the warning for me selectively only for the stuff that gets loaded from overrides. You can, of course, be even more selective with your folder naming. It also means I don't have to change anything in my MATLAB system files so it's localized to my user account and persistent across upgrades (for good or bad; monkey patch responsibly).
To access the built-in figure from my override, I have to cd there temporarily (as otherwise the override will simply call it self). So figure.m would look like this:
function fig = figure(varargin)
% Call original figure function
old = pwd;
cd(fullfile(matlabroot, 'toolbox', 'matlab', 'graphics', ''));
fig = figure(varargin{:});
cd(old);
% ...
% Do dirty override magic
end
I can't comment yet, so I'll just expand the answer given by vicvicvic further here. The general process stays the same, however it has some further fine tunings.
Put your override-function figure.m in a folder which is not on your current MATLAB path, e.g. /users/heidelberg/.matlab/_overload. For me, tilde expansion is supported, but I would not rely on it. However, you could also put it in a subfolder of a MATLAB startup script (see below).
Use startup.m to add your override folder to the path. To avoid the warning, make sure it is turned off, and then restore its original state
% save the current state while switching it off
warningState = warning('off', 'MATLAB:dispatcher:nameConflict');
addpath('/users/heidelberg/.matlab/_overload');
% restore the saved state
warning(warningState);
% cleanup
clear('warningState');
The difference here is that if e.g. your administrator set the warning to be off anyway, you won't accidentally switch it back on.
In your implementation of figure, at some point you will probably have to call the builtin version. vicvicvic suggested a cd to the directory, however there also is the MATLAB function builtin, which does that job for you:
function fig = figure(varargin)
% overload function
% call builtin figure
varargout = cell(1, nargout);
[varargout{:}] = builtin('figure', varargin{:});
% do you magic here
% ...
end
Also, use varargout and nargout to preserve for an arbitrary number of output arguments (might be irrelevant here and now, but for other functions or future releases it might be important).
Annotation
A method I prefer is to have a subfolder in the directory where my startup.m file is stored, called e.g. _overload. For me this is /users/timm/Documents/MATLAB/_overload. To easily add this folder, use the following script:
File /users/timm/Documents/MATLAB/startup.m
% extract the current directory (pwd can fail if started elsewhere)
[currentPath, ~, ~] = fileparts(mfilename('fullpath'));
% add the path, compare above
warningState = warning('off', 'MATLAB:dispatcher:nameConflict');
addpath([currentPath, filesep(), '_overload']);
warning(warningState);
% cleanup
clear('currentPath', 'warningState');
Adding a directory that contains the function overload to the search path will display the warning whenever a function in that directory is edited and saved, no matter if the directory is added in startup.m or not.
A simple way to solve this is to put overloading functions in a package. Then import the package in startup. No need to mess with warnings.