General
Follow


Share your favorite snippet or utility

Matt Fig on 20 Sep 2012
Latest activity Reply by DGM on 23 Feb 2023

I am wondering what others use for those little short-cuts or niceties in MATLAB. I have in mind something you wrote or something somebody else wrote or an underused MW function.
Here are my two favorites.
This is a simple script I use. Here is the entire contents of CLC.m (yes, it is capitalized):
clear all,close all,clc
Very simple, but I use it all the time. Here is another one I use so often that I forget not every machine has it (though every machine should, IMO):
Here is an underused MW function that I occasionally employ when working on someone else's machine. The usual response is, "Wait, what did you just do?"
home
What are some of yours?
DGM
DGM on 23 Feb 2023
For some reason, I can never remember the name of the lookfor() function, and looking for the lookfor() function is a pain when you don't know what it's called.
So I just called it what I expected it to be called
apropos 'modified bessel'
besseli - Modified Bessel function of first kind besselk - Modified Bessel function of second kind besseli - Modified Bessel function of the first kind for symbolic expressions besselk - Modified Bessel function of the second kind for symbolic expressions
Darik
Darik on 21 Sep 2012
I'm a clumsy typist...
function hepl (x)
help (x)
end
Sean de Wolski
Sean de Wolski on 21 Sep 2012
Tyop corrections in R2012b!!
hepl fmincon
Undefined function 'hepl' for input arguments of type 'char'.
Did you mean:
>> help fmincon
I already highlighted this as my second favorite new feature:
Matt Fig
Matt Fig on 21 Sep 2012
@Sean, I have only the command window and a minimized command history open to the left of that space. No docked anything. I am old-school. That is why I like whats so much, one simple command and I can do it all and I don't have to keep any more panels open all the time. Let me know "what" you think if you try it.
Image Analyst
Image Analyst on 21 Sep 2012
Is there any way to make a shortcut button called something like "Format Code" which essentially does Control-A (to select all the text in the editor window) followed by Control-I (to fix up the indenting/alignment)? That's a nice set of utility commands that I use often.
Image Analyst
Image Analyst on 21 Sep 2012
Thanks - it works!
Sean de Wolski
Sean de Wolski on 21 Sep 2012
This should be it's own question because I want 4 points :)
smartIndentContents(matlab.desktop.editor.getActive)
Sean de Wolski
Sean de Wolski on 21 Sep 2012
@Matt, do you not keep the current directory panel open? I might have to give whats a try if it means I could close that panel.
Shane
Shane on 21 Sep 2012
I use uigetfile and uigetdir day in and day out, so when I am writing a new code I always add this code to the beginning of my function and I love it:
if isappdata(0,'previousDirectory')
startDirectory=getappdata(0,'previousDirectory');
if isnumeric(startDirectory)
startDirectory='C:\';
end
else
startDirectory='C:\';
end
[uigf1 uigf2]=uigetfile('*.bdf','SelectFile to Load',startDirectory);
setappdata(0,'previousDirectory',uigf2);
Simply saves my directory location so that I dont start at C:\MyDocuments|MATLAB every time.
Robert Cumming
Robert Cumming on 21 Sep 2012
Downloaded whats for the first time - very handy! :)
Srinivas
Srinivas on 20 Sep 2012
I have a lazy shortcut to open the current folder I am working in
system(strcat('%SystemRoot%\explorer.exe',' "',pwd,'"'));
:)
Ashish Uthama
Ashish Uthama on 21 Sep 2012
winopen .
:)
Jan
Jan on 20 Sep 2012
Even "%SystemRoot%\explorer.exe" will work under Windows only, Sean.
Sean de Wolski
Sean de Wolski on 20 Sep 2012
@Matt: only on Windows..!
Matt Fig
Matt Fig on 20 Sep 2012
Also, this is lazier!
winopen(pwd)
Robert Cumming
Robert Cumming on 20 Sep 2012
I second home - its very useful, the number of times I've had to go to a colleagues screen to help them debug and they have typed clc thinking they are helping me start - but of course that clears the error and any messages on the screen....
My favourite - its not a snippet but a code I would struggle to do wihtout since I work on multiple project is my SaveEditorHistory FEX.
Daniel Shub
Daniel Shub on 20 Sep 2012
@Sean, I cannot get dbquit to be recursive, but adding the following makes it so calling it twice works
if feature('IsDebugMode')
disp('MATLAB was in debug mode, cll must be run a second time.')
dbquit('all');
end
Sean de Wolski
Sean de Wolski on 20 Sep 2012
  • gohome
%Go home
cd('H:\Documents\MATLAB');
  • fgcf
figure(gcf);
I used this through grad school since I would always lose my figures on the Mac. Since starting here, I discovered the very similar shg() and have made the transition.
  • thesaurus
function thesaurus(word)
%SCd 07/19/2010
%Function to look up synonyms to input word.
%
%Uses www.thesaurus.com
%
%How to use:
% thesaurus('useful')
% thesaurus useful
% thesaurus 'useful'
%
web(['http://thesaurus.com/browse/' num2str(word)],'-browser');
end
  • Sean (my vanity function)
function Sean(varargin)
%Sean is awesome
fprintf('\b is awesome!\n');
end
Is defaulted in my startup.m file
  • vec
function v = vec(m)
%Helper function to turn a matrix of any size into a column vector using (:)
% This function is meant to make one-line computations easy/fast when
% subscripting already.
%SCd 01/04/2011 (First function of 2011!)
%
%Updates: -05/24/2011: Used reshape instead of colon for speed.
%
%Usage: v = vec(m)
%
%Example:
% %Original way to one line the median of a slice of 3d matrix:
% M = repmat(magic(200),[1 1 200]); %200x200x200 magic squares
% Mmed = median(reshape(M(:,:,34),[],1)); %34th slice
%
% %Using the vec() function
% Mmed = median(vec(M(:,:,34)));
%
%Input Arguments:
% -m: matrix of any size
%
%Output Arguments:
% -v: m(:)
%
%See Also: colon reshape
%
v = reshape(m,numel(m),1);
end
  • wpwd
function wpwd
%winopen(pwd)
winopen(pwd)
end
Sean de Wolski
Sean de Wolski on 21 Sep 2012
@Daniel, so:
x((1:numel(x)).')
?
It's about 2000x slower on my system:
t1 = 0;
t2 = 0;
for ii = 1:100
tic
v = reshape(m,numel(m),1);
t1=t1+toc;
tic
v2 = m((1:numel(m))');
t2 = t2+toc;
end
t2/t1
Reshape is blazingly fast since it just modifies some header information.
Daniel Shub
Daniel Shub on 21 Sep 2012
Sean can you elaborate on "Updates: -05/24/2011: Used reshape instead of colon for speed." Have you thought about just using linear indexing instead of the reshape?
Matt Fig
Matt Fig on 20 Sep 2012
Thanks for sharing these, Sean!
Sean de Wolski
Sean de Wolski on 20 Sep 2012
I call mine cll contents:
%Nuke it from Orbit!
close all force;
clear;
clc;
Note I don't do clear all (and try to never do it) since I like keeping the JIT happy.
I also tried to add a recursive dbquit into this but could not get it to actually work.
Albert Yam
Albert Yam on 20 Sep 2012
home
Just blew my mind.
Albert Yam
Albert Yam on 20 Sep 2012
I have a few shortcut buttons. I have the clear all; clc separate from the close all though (and an fclose(all)). I have one specifically for looking at figures, which I use pretty often.
set(gcf, 'Position', [100 50 850 600])
But the most useful one I have is,
addpath (genpath (pwd))
disp('ADD path ''pwd''')
Another 2 I have are savez and diaryz, which just add a time stamp in the filename.
Daniel Shub
Daniel Shub on 20 Sep 2012
I have three versions of your CLC that I have as shortcuts. They all came from here
The biggest hammer is
!matlab &
exit
This sometimes causes issues with the command window moving and files needing to be closed, but it really gets the job done. The second is a slightly smaller hammer that is based on the longer answer to the question. The third is the same as the second, except it doesn't screw with the path, current directory, or command window contents.
On my computer get(0, 'MonitorPosition') returns nonsense so I use
function MonitorPositions = getmonitorpositions()
error(nargchk(0, 0, nargin, 'struct'));
error(nargoutchk(0, 1, nargout, 'struct'));
Monitors = ...
java.awt.GraphicsEnvironment.getLocalGraphicsEnvironment.getScreenDevices;
MonitorPositions = zeros(length(Monitors), 4);
for iMonitors = 1:length(Monitors)
MonitorBounds = Monitors(iMonitors).getDefaultConfiguration.getBounds;
MonitorPositions(iMonitors, :) = ...
[MonitorBounds.getX, MonitorBounds.getY, ...
MonitorBounds.getWidth, MonitorBounds.getHeight];
end
end
I also like
function [UserNameString, HostNameString, IpAddressString, MacAddressString] = getcomputer()
error(nargchk(0, 0, nargin, 'struct'));
error(nargoutchk(0, 4, nargout, 'struct'));
UserNameString = char(java.lang.System.getProperty('user.name'));
HostNameString = char(java.net.InetAddress.getLocalHost.getHostName);
Eth0Obj = java.net.NetworkInterface.getByName('eth0');
MacAddressString = sprintf('%c%c-%c%c-%c%c-%c%c-%c%c-%c%c', dec2hex(mod(double(Eth0Obj.getHardwareAddress()), 256))');
Temp = Eth0Obj.getInterfaceAddresses.size-1;
IpAddressString = sprintf('%d.%d.%d.%d', mod(double(Eth0Obj.getInterfaceAddresses.get(Temp).getAddress.getAddress), 256));
end
Image Analyst
Image Analyst on 20 Sep 2012
I have another few shortcut buttons on my toolbar to quickly go to often-used folders and show the file panel. For example one button that says "Go to demos folder" and in there is this code:
cd('D:\MATLAB\work\Demos');
filebrowser;
I keep all my demos that I post here in Answers (that are worthy of keeping) in that folder.
Matt Fig
Matt Fig on 20 Sep 2012
IA, I gave a link in the OP to whats. Here is another:
The function shows all M-files, MAT-files and figure files in the directory as hyperlinks. Clicking on a M-file name opens the file for editing. Clicking on a MAT-file name loads the file. Clicking on a figure file opens the figure.
Image Analyst
Image Analyst on 20 Sep 2012
I don't have a "whats" function - I don't know what's that (no pun intended). I put in "filebrowser" because I used tabbed panels for workspace and the file listing to conserve space for code. So if I had been looking at the Workspace panel and just cd'ed then I wouldn't see my files, which was the whole point of going to that folder in the first place. So I do filebrowser and it sends the workspace panel to the back and brings the file listing panel to the forefront. Even if you aren't using tabbed panels, it can't hurt. If you had closed the panel for some reason, filebrowser will bring it back.
Daniel Shub
Daniel Shub on 20 Sep 2012
At one point I tried to develop a way of using the history better. Basically I wanted functions like projectStart, projectEnd, and projectRestore that would handle the path and scrape the history for the last time I worked on the project. Never really figured out how it would work, but I still think it would be a cool utility.
Matt Fig
Matt Fig on 20 Sep 2012
I am already plotting how to use this. I have a folder where I keep all of the utility files I wrote. Sometimes I want to go there and add a new utility, which means I will have to go up to the Current Folder dropdown and find my folder. Now I will just type:
utilityfolder
which calls an M-file by the same name. Inside that M-file is the command:
CLC
cd('C:\Users\matt fig\Documents\MATLAB\MF_Tools')
whats
Thanks, IA!
Matt Fig
Matt Fig on 20 Sep 2012
Yeah, I used to have a shortcut button with that code but found that I would rather type than click. Personal preference, I guess.
Image Analyst
Image Analyst on 20 Sep 2012
That's what the Mathworks folks recommend also - I learned that in one of their training classes long ago. They had us create a shortcut button on the toolbar called "cleanup" and that code was in there.
José-Luis
José-Luis on 20 Sep 2012
Not really a snippet, but useful.
Sean de Wolski
Sean de Wolski on 21 Sep 2012
keep also safe guards against deleting things when you have a typo.
per isakson
per isakson on 21 Sep 2012
Better name and fewer keystrokes. keep has been around for a long time. I for one hadn't noticed "clearvars -except"
Ilham Hardy
Ilham Hardy on 21 Sep 2012
What exactly the difference compared to
clearvars -except
??
Sean de Wolski
Sean de Wolski on 20 Sep 2012
I love keep
Matt Fig
Matt Fig on 20 Sep 2012
Thanks, Jose! I edited your answer to put in the link for others. I'll check that one out! It may not be a snippet, but it is a utility, I think.
José-Luis
José-Luis on 20 Sep 2012
It's in the file exchange. Forgot about that:
Matt Fig
Matt Fig on 20 Sep 2012
>> help keep
keep not found.
What version are you using?