How to remove the variable "clear" in MATLAB - 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.

Related

Removing preallocating warning when preallocating is done in another file

I have some parameters changing size on every loop iteration in main.m. I have placed the preallocations in another script called preallocation.m.
When the preallocations is placed in another script, I get a warning from Matlab for every parameter in the main script about concidering preallocating for improved speed.
Is there a way to remove these warnings? If I add another parameter that needs preallocating and forget to preallocate, I'd like to get a warning for that parameter.
I'd be tempted to make your preallocation script a function. Then you could write something like
[myvar1,myvar2,myvar3] = preallocate();
This would allow you to see all preallocated variables at a glance and would also keep mlint quiet.
In my MATLAB version (R2014b) this is done by right-clicking on the variable that has the squiggly red line onder it, and then selection the option Suppress "The variable myVar appears to...". You can then choose to suppress this single line, all warnings of this type in the entire file, or all warnings of this type in all files.
edit: if your MATLAB version does not have this context menu option, you can add %#ok<SAGROW> to the end of the offending line, like so:
someVar(ii+1) = someVar(ii) + someConstant; %#ok<SAGROW>
If you are hell-bent on not wanting these warnings and not using a preallocation function that returns many variables, you could also do the following:
function init = preallocate()
init.a = some stuff;
init.b = some stuff;
...
end
%% actual script
init = preallocate()
structvars(init); % using structvars from file exchange
structvars can be found here. Note that I haven't tried the package myself, so I am unsure as to how well it will work and how fast it is.

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

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.

How does scoping in Matlab work?

I just discovered (to my surprise) that calling the following function
function foo()
if false
fprintf = 1;
else
% do nothing
end
fprintf('test')
gives and error Undefined function or variable "fprintf". My conclusion is that the scope of variables is determined before runtime (in my limited understanding how interpretation of computer languages and specifically Matlab works). Can anyone give me some background information on this?
Edit
Another interesting thing I forgot to mention above is that
function foo()
if false
fprintf = 1;
else
% do nothing
end
clear('fprintf')
fprintf('test')
produces Reference to a cleared variable fprintf.
MATLAB parses the function before it's ever run. It looks for variable names, for instance, regardless of the branching that activates (or doesn't activate) those variables. That is, scope is not determined at runtime.
ADDENDUM: I wouldn't recommend doing this, but I've seen a lot of people doing things with MATLAB that I wouldn't recommend. But... consider what would happen if someone were to define their own function called "false". The pre-runtime parser couldn't know what would happen if that function were called.
It seems that the first time the MATLAB JIT compiler parses the m-file, it identifies all variables declared in the function. It doesn't seem to care whether said variable is being declared in unreachable code. So your local fprintf variable immediately hides the builtin function fprintf. This means that, as far as this function is concerned, there is no builtin function named fprintf.
Of course, once that happens, every reference within the function to fprintf refers to the local variable, and since the variable never actually gets created, attempting to access it results in errors.
Clearing the variable simply clears the local variable, if it exists, it does not bring the builtin function back into scope.
To call a builtin function explicitly, you can use the builtin function.
builtin( 'fprintf', 'test' );
The line above will always print the text at the MATLAB command line, irrespective of local variables that may shadow the fprintf function.
Interesting situation. I doubt if there is detailed information available about how the MATLAB interpreter works in regard to this strange case, but there are a couple of things to note in the documentation...
The function precedence order used by MATLAB places variables first:
Before assuming that a name matches a function, MATLAB checks for a variable with that name in the current workspace.
Of course, in your example the variable fprintf doesn't actually exist in the workspace, since that branch of the conditional statement is never entered. However, the documentation on variable naming says this:
Avoid creating variables with the same name as a function (such as i, j, mode, char, size, and path). In general, variable names take precedence over function names. If you create a variable that uses the name of a function, you sometimes get unexpected results.
This must be one of those "unexpected results", especially when the variable isn't actually created. The conclusion is that there must be some mechanism in MATLAB that parses a file at runtime to determine what possible variables could exist within a given scope, the net result of which is functions can still get shadowed by variables that appear in the m-file even if they don't ultimately appear in the workspace.
EDIT: Even more baffling is that functions like exist and which aren't even aware of the fact that the function appears to be shadowed. Adding these lines before the call to fprintf:
exist('fprintf')
which('fprintf')
Gives this output before the error occurs:
ans =
5
built-in (C:\Program Files\MATLAB\R2012a\toolbox\matlab\iofun\fprintf)
Indicating that they still see the built-in fprintf.
These may provide insight:
https://www.mathworks.com/help/matlab/matlab_prog/base-and-function-workspaces.html
https://www.mathworks.com/help/matlab/matlab_prog/share-data-between-workspaces.html
This can give you some info about what is shadowed:
which -all
(Below was confirmed as a bug)
One gotcha is that Workspace structs, and classes on the path, have particular scoping and type precedence that (if you are me) may catch you out.
E.g. in 2017b:
% In C.m, saved in the current directory
classdef C
properties (Constant)
x = 100;
end
end
% In Command window
C.x = 1;
C.x % 100
C.x % 1 (Note the space)
C.x*C.x % 1
disp(C.x) % 1

How to interrupt MATLAB IDE when it hangs on displaying very large array?

Suppose I'm using the MATLAB IDE and happen to have some very large objects in my workspace (e.g. arrays of 500k+ elements). Now, suppose that I stupidly and accidentally double click on one of these very large variables, which triggers a load to the array editor. Unfortunately, with arrays this big, MATLAB just hangs.
I've tried CTRL+C, CTRL+BREAK, CTRL+D, but none seem able to interrupt the behavior of the IDE. I know I can force matlab to quit, but reading all of those variables into the workspace in the first place takes a lot of time, and I may have unsaved changes in an editor window, etc.
The variable editor is launched using the command openvar. To solve your problem you can take advantage of a Matlab quirk that causes functions to be masked by variables with the same name. For example if you create a variable named plot the plot() function stops working.
The solution, although hackish, is to simply create an empty variable named openvar. Then anytime attempt to open the variable editor will fail because the function openvar is being hidden by the variable.
If you want to use the variable editor again simple call clear openvar to delete the variable and the function will be unmasked.
I found a way, but it's not the best, it requires a change of path and back once to get a handle to the original openvar
function openvar(name,array)
persistent org_openvar
if isempty(org_openvar)
curdir=pwd;
cd(fullfile(matlabroot,'toolbox/matlab/codetools'));
org_openvar = #openvar;
cd(curdir);
end
if numel(array)>1e5
if strcmp(questdlg(sprintf('Opening ''%s'' which has %d elements.\n\nAre you sure? This is gonna take a while!',name,numel(array)), ...
'Variable editor','Yes','Cancel','Cancel') , 'Yes')
org_openvar(name,array)
end
else
org_openvar(name,array)
end
end
getting that handle is the biggest problem, calling it is just fine. If openvar would be built in, you could use the function builtin:
builtin('openvar',name,array)
but this is unfortunately not the case :(
str2func in combination with the complete path also doesn't work, at least I don't get it to work...

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.