# What’s in Your startup.m?45

Posted by Loren Shure,

Several of us at The MathWorks were recently discussing how we each use startup.m.

### What is startup.m?

I typically don't use startup.m, but when I do, I have one sitting in a particular directory where there's other code I want to use as well. And I make a MATLAB shortcut in that directory (this is using Windows) that specifies this particular directory as the starting location for MATLAB. When you use this icon for starting MATLAB, it starts in the specified directory, and finds and runs the startup.m located there. I usually do this for presentations that I give, so my startup.m generally includes commands that change default font sizes for figures so the annotations are visible in a large, dimly lit room. I have also helped users customize their own startup.m. Commonly, the contents again includes commands to set up preferences for graphics, for example, to have grid on by default (use something like this: set(0,'defaultAxesXGrid','on'), and similarly for 'YGrid' and 'ZGrid'). I've also seen users randomize the starting point for creating random numbers.

### finish.m Anyone?

The analog to startup.m is finish.m. This can be used to save data, ask for confirmation to quit, release a hardware resource, finish writing out a file, etc.

### What Do You Use startup.m For?

Do you use startup.m or finish.m? If so, I'd love to hear what you put in these. Post your thoughts here.

Get the MATLAB code

Published with MATLAB® 7.7

Markus replied on : 1 of 45

Hi Loren,

my startup.m is very short and depends on the machine where I run Matlab:


cd C:\Markus\Anwendungsdaten\MATLAB\functions
startuplocal


The file startuplocal.m is the same on every machine, I synchronize it between hosts. It has really a lot in it:


function startuplocal(projectName)

% set computer-specific directories (functionsDir implicitly defined)
hostname = gethostname;
switch [username '@' hostname]
case 'Markus@Elroy'
homeDir     = 'C:/';
case {'m104@ameise', 'm104@linse2', 'm104@linse4'}
homeDir     = '/raidar1/m104/';
case 'Markus@CMTCL073114'
homeDir     = 'C:/Daten/Projekte';
otherwise
disp(textwrap2(sprintf(['Warning: Computer %s and/or username %s unknown. ', ...
'Set directories in %s and restart function. Home directory and temporary', ...
'directory are mandatory.'], hostname, username, mfilename)));
return
end

% set random state
rand ('state', sum(100*clock));
randn('state', sum(100*clock));

% set command window format
format compact
format short g

% turn beep on
beep on

% set some other default values
set(0, 'RecursionLimit', 50);
set(0, 'DefaultFigurePaperType', 'A4');
set(0, 'DefaultFigureWindowStyle', 'normal');
set(0, 'DefaultAxesBox', 'on');
set(0, 'DefaultTextFontSize', 14);
set(0, 'DefaultAxesFontSize', 16);
set(0, 'DefaultUicontrolFontSize', 8);
recycle('off');
warning on all
warning on backtrace

% select project
if ~exist('projectName', 'var')
projectName = 'other'; % initialize
while strcmp(projectName, 'other')
projectName = questdlg('Select project to start.', ...
'MATLAB project selection', 'differentialevolution', 'multicore', 'other', 'differentialevolution');
if strcmp(projectName, 'other')
projectName = questdlg('Select project to start.', ...
'MATLAB project selection', 'contest', 'assignment', 'none', 'contest');
end
end
end

% set project-dependent directories
switch projectName
case 'contest'
projectDir = concatpath(homeDir, 'Markus/Anwendungsdaten/MATLAB/contest/armyants');
case 'differentialevolution'
projectDir = concatpath(homeDir, 'Markus/Anwendungsdaten/MATLAB/differentialevolution');
case 'multicore'
projectDir = concatpath(homeDir, 'Markus/Anwendungsdaten/MATLAB/multicore');
case 'assignment'
projectDir = concatpath(homeDir, 'Markus/Anwendungsdaten/MATLAB/assignment');
case 'none'
projectDir = '.';
otherwise
error('No project selected or project unknown.');
end

% move to project directory
cd(projectDir);

% start function init.m if existing
if exist(fullfile(projectDir, 'init.m'), 'file')
init;
end


I already shortened it a lot. What it also does is

* run M-Lint over all files

* check if all files have Matlab-style comments

* run make over all my mex files

Yours
Markus

Scott replied on : 2 of 45

I use startup.m to create a new log file for each session of MATLAB that keeps sessions independent of each other. I also set my output format (format long g; format compact;).

In finish.m, I close the log file.

I’ll post the code in a separate comment when I get the chance. I don’t have it with me at the moment.

Dan replied on : 3 of 45

I use finish.m to save my workspace, path, and current directory to a temporary file and then I have a shortcut that reloads all this data so that I can start exactly where I left off the day before by clicking the shortcut.

Ian replied on : 4 of 45

I use startup.m for three things at the moment.

1) dbstop if error – so when I’m debugging my code, it will automatically stop when it hits an error, instead of just reporting the error and clearing it. Saves me a lot of time and effort.

2) format long g – I can’t stand not having the format set to anything less.

3) Turning off warnings. Currently the only one I have set is warning(‘OFF’,’MATLAB:Axes:NegativeDataInLogAxis’) – I do a lot of printing plots on loglog axis, and I just got tired of dealing with this error. I’m sure there are some other errors I should add, like the one for calling functions when you don’t have the capitalized correctly, but I haven’t gotten around to adding that in yet.

BTW, I want to thank you for this blog – I’m a long time lurker, and I love it. It’s such a great resource!

Sven replied on : 5 of 45

I use startup.m almost exclusively to add my “_includes” folder (and its subdirectories) to the path.

My _includes folder consists of my own little file exchange of all the submitted programs that I download, along with my own folder of m files.

On my own computer, I keep it in the default MATLAB startup directory. However, I also want these files available to others to use my “_includes” when they run a program I’ve written. Therefore I place a copy of the “_includes” on a network location. In previous versions, I think the default startup directory was “Programs Files/MATLAB/work”, so I used to just add a single startup.m file there. Now however, this has moved to each user’s own Documents & Settings location.

Therefore, I have cheated *gasp*, and hard coded the call to addpath() into the matlabrc.m file on each machine, rather than into a startup.m file. I am quite certain this is very bad form, and I will probably be struck down by a MATLAB-logo-shaped bolt of lightning in the near future. Is there a better way to ensure that any user who runs MATLAB on a given machine starts with the same startup.m file?

Cheers,
Sven.

Loren replied on : 6 of 45

All,

Thank you so much for sharing your information with us. It’s really interesting to see the common features and the special angles from you.

Ian – a small point, but you can change the format in the preferences panel (look under the File menu) and it will persist across sessions.

–Loren

Yakov replied on : 7 of 45

I use startup.m to keep values of physical constants in SI units. I also call it from functions to import these constants into the function workspace.

Iain replied on : 8 of 45

The startup.m in my $MATLABPATH does several of the things listed above. I too set format there, which I prefer to clicking in a GUI that I never load and having the preference saved in the bowels of some Matlab state that I don’t understand. Here’s a snippet that I use to make Matlab spot when it is run inside a “testing” directory and to include the parent directory containing the code to be tested: % Encourage me to separate out tests into a subdirectory, by making it easier to % do so. Then I’m less likely to delete tests and more likely to organize them % well and run them. if regexp(pwd,’/test(ing|s|)(|_)(|stuff|rig)$’)
end

As in Loren’s post, I sometimes have startup.m files for particular projects. I like to load the global startup too, so I usually include:

% run usual startup script
startups = which(‘startup’, ‘-ALL’);
if length(startups) > 1
run(startups{2})
end

Alex replied on : 9 of 45

Can i with use of startup.m to set two different configurations? For example: when i’m working i would like to have one set of fonts, colors (also in the cmd) when i’m during lecture/presentation to switch to other configuration (bigger fonts etc..).

Daniel replied on : 10 of 45

I never used a startup.m. I have an init.m in the folder for each project that I work on which is the first thing I run. However, I think I will take 5 minutes to write one for some general stuff.

It will probably include
format long g
grid on by default (Why oh why isn’t this the factory default?)
Close down all files in the editor (The open files will not necessarilly be on the path causing undefined behaviour if they are run)

–DA

Cris Luengo replied on : 11 of 45

For our DIPimage toolbox, we direct users to add some commands to their startup.m file: one ADDPATH command and the command to initialize the library that the toolbox is built on. I think it’s a clean solution keeping these two together, rather than saving the toolbox directory in the default path and running the risk of people forgetting to call the initializing command.

The startup.m file is also an excellent place to set default behavior for this toolbox, since we don’t yet have any preferences persistent across sessions.

I also cannot live without this one in my startup.m file:
set(0,’DefaultFigurePaperPositionMode’,’auto’)

David Schwartz replied on : 12 of 45

I use them to save and restore the current directory.

% startup.m
cwd = getpref(‘Startup’,’dir’,pwd);
cd(cwd);
disp(sprintf(‘Current directory: %s’,cwd))
clear cwd

% finish.m
setpref(‘Startup’,’dir’,pwd);

Hosam Aly replied on : 13 of 45

My startup.m adds the startup directory and all directories inside it. It also logs all command window input and output to a file to be easily accessible later.

addpath(genpath(pwd)); diary diary.txt 

Wes replied on : 14 of 45

I set the random seeds based on the current time. Also, there’s some matlab path and dynamic java path setup.

“… I usually do this for presentations that I give, so my startup.m generally includes commands that change default font sizes for figures so the annotations are visible in a large, dimly lit room.”

What I would find really useful here is a way to programmatically increase the command-window/editor/etc text size and set the font to bold when giving a presentation in a large room. The closest I ever got was finding a system_dependent/feature call which could get the current text size&weight, but haven’t found how to set them. Of course, now somebody will point out some obvious piece of doco which I’ve missed which says how to do this.

Daniel replied on : 15 of 45

So, after getting some help in the forums, this is what I have:

 

%% Initialize the system with defaults

%% Set grids on all axis.
set(0,'defaultAxesXGrid','on');
set(0,'defaultAxesYGrid','on');
set(0,'defaultAxesZGrid','on');

%% Set the display format
format compact;
format long g;

%% Close all editor files.
editorServices = com.mathworks.mlservices.MLEditorServices;
editorServices.closeAll();

%% And finally put down anything ye have brought forth
clear all;
 

Loren replied on : 16 of 45

Folks-

The feedback continues to fascinate me. Especially as I see differences in workflow from how I do things… Without formal projects, I tend to leave lots of files open in MATLAB to help remind me what I am working on. Many of you seem to prefer to start from a blank slate w.r.t. editor documents.

Trying to characterize the input so far, the main themes I see are: setting “preferences” such as graphics defaults, numeric formats, warning and debug states, initializing constants or randomizing the state for random number generation, closing files, session logging, and inter-session continuity. What a mixed bag, but with some notable trends!

Thanks again. And please feel free to keep adding to this thread.
–loren

lehalle replied on : 17 of 45

according to me, the advantage of startup.m is to be sure that on every computer you will be able to run your codes. in my group we use surround as source control software, so the goal is that if you take a computer, install matlab on it, get the sources (including the startup.m), all will work.
first we mount all our paths in the startup.m
we have a structured architecture of directories, in some of them when the startup.m find a file with a given name (and if it is a script) he evaluate them. it allows to mount branches: if you take the directory and its subdirs on the source control, the special paths will be added.
some automatic documentation of code is also performed by the startup.m

then we began to use MDCE…
it implied a lot of changes, so the startup.m had to be used to store environment variables, accordingly to the name of the machine (our startup.m is not multi environment), and finally we decided to store a lot of info in an xml file that is loaded by the startup.m
now the stratup only apply functions to the content of the .xml file (its name is st_work.xml, like “structured work”) and all the specific part is in the .xml file…

Michael replied on : 18 of 45

I’m not much of a fan of startup.m files. At most I will put things like a FORMAT statement in there. When it gets to the point that you’re changing paths and loading data sets and doing project-specific things it can become frustrating. It’s easy to forget that something important is in your startup.m file and wonder why something isn’t working exactly as expected on a different machine.

This is one of the primary advantage of FORTRAN. Care is taken to ensure that some set of commands produces common results across compilers. More flexibility is not good when it promotes bad programming practice.

Val Schmidt replied on : 19 of 45

My startup.m contains mostly formatting options for plots. I never find that the default plot options produce a very nice looking and readable plot, so I try to adjust them for things I do frequently here.

-Val

set(0,’DefaultFigurePosition’, [25 550 500 400]);
set(0, ‘DefaultAxesFontSize’, 12);
set(0, ‘DefaultAxesFontName’, ‘Helvetica’);
set(0, ‘DefaultAxesFontWeight’,’bold’);

John replied on : 20 of 45

On the lighter side…this is the output of my startup file (complete with a case for which part of the day it is) … can you tell I’m a fan of War Games.

Toolbox Path Cache read in 0.08 seconds.
MATLAB Path initialized in 0.06 seconds.
Startup file M:\AnastML\startup.m executing…
Good afternoon Dr. Anast … would you like to play a game?? (-;

Loren replied on : 21 of 45

Looks like the theme of setting graphics defaults continues. And I love the injection of fun, John!

–Loren

Jonas replied on : 22 of 45

I have a startup.m in every installation of Matlab. It adds the current user’s home/matlab directory and all subdirectories to the path, and it runs svn update on all of the user-generated code to ensure everyone is working with the latest version of the code.

Tom Elmer replied on : 23 of 45

I have a project that I only work on on Tue apart from any other projects I am working on. Also, I alternate Mondays between that project and the others. So, my finish.m saves my environment to different locations depending on a) if it’s Tue, or b) if I’m in a certain directory tree. Then my startup by default loads a different workspace if it is Tue or not. However, if it happens to not be Tue and I want to work on the Tue project, I also have a shortcut on my shortcuts bar that sets a flag, then reruns startup.m (which checks the flag then clears previous memory).

Sebastiaan replied on : 24 of 45

I started using startup.m to disable opengl hardware rendering:
opengl software

This is because I (and a lot of others) connect to a remote machine through xdmcp, and then hardware rendering is not available, or at least not sophisticately supported. 3D figures are displayed corrupted (full window, figure always in lower-left of the screen). Forcing software rendering overcomes this problem.

Jody Klymak replied on : 25 of 45

Can matlab somehow save the editor state? That is far more important to me than saving the workspace.

Loren replied on : 26 of 45

Jody-

What specific editor state do you mean? breakpoints? Or where the cursor is? The editor can already be set up to re-open existing files (via preferences).

–Loren

Jody Klymak replied on : 27 of 45

Loren-

Sorry, I wasn’t clear. If I am working on project A I have a.m, b.m and c.m open. If I switch to project X I want to close those, and open x.m, y.m and z.m. If I switch back to project A, a,b, and c would reopen.

Folks save their workspaces, or desktop layouts, but you can’t save your what files you have open.

I don’t tend to use breakpoints, etc. but maybe that would be useful in addition.

Thanks, Jody

Daniel replied on : 28 of 45

Jody:
Should be easy with a java trick I just learned. Run this to save a list of files open in the editor. This is supposedly undocumented functionality, so keep an eye out.


editorServices = com.mathworks.mlservices.MLEditorServices;
editorState = editorServices.builtinGetOpenDocumentNames();
save ( 'editorState.mat', editorState' );


And this to restore the editor


editorServices = com.mathworks.mlservices.MLEditorServices;
load ( 'editorState.mat' );
for i = 1:length(editorState)
editorServices.openDocument( editorState(i) )
end

Jody Klymak replied on : 29 of 45

Hi Daniel,

That works great, and the possibilities are kind of endless.

Thanks for the tip!

Cheers, Jody

Martin replied on : 30 of 45

Hi Daniel:
I tried your suggestion without success. I got this error

??? Error using ==> ctranspose
Transpose on an array with opaque indexing is not defined.

Martin

per isakson replied on : 31 of 45

Hi Martin

editorState = cellstr( char( editorState ) );


to convert the Java string to a cell array of strings.
In R2208a save cannot handle Java strings.

/per

Martin replied on : 32 of 45

/per

I tried that and got this new error:

??? Error using ==> save
Argument must contain a string.

Error in ==> saved_editor_space1 at 8
save ( ‘editorState.mat’, editorState’ );

Loren replied on : 33 of 45

Martin and Per-

I wonder if you can work this out off-line and then post the solution.

–Loren

Ben replied on : 34 of 45

Martin,

I think you’ve used cut+paste from your web browser and ended up with some fancy typographic quotes. Retype the commands in the Matlab editor which doesn’t silently replace quotes, and things should get better.

And to get back on topic, I like to include all plot customizations and so forth in the script that creates the plot, then if I go back and remake a plot I’ll get the same result, whereas if I put all of that into startup.m then every time I made changes I’d end up changing the behavior of my existing scripts.

Martin replied on : 35 of 45

The problem was that there is a comma missing in the command save ( ‘editorState.mat’, editorState’ );

i.e. it should read as follows:
save ( ‘editorState.mat’, ‘editorState’ );

It works for me now. This will prove to be very useful.

Anne replied on : 36 of 45

Thank you everyone for the code to save and reload the editor state. I’ve been looking for a way to do this. It is very helpful.

Oscar replied on : 37 of 45

Thanks Daniel, that is so cool, have been wondering why the mathworks guys have never added an option to do that.

OysterEngineer replied on : 38 of 45

This post was really handy just because I learned how to default the grid on.

Here is my question: Why isn’t this capability default setting capability mentioned in the FRP for grid? Instead, it is buried 3 layers deep in the general discussion of Graphics.

Also, what does it mean when the 1st example sets a default for the gcf, while a few lines later is says, “It is meaningful to specify a default figure color only on the root level.”? In your example, I guess you are setting grid to on at the root level, assuming that a handle value of 0 is the same as the root level.

Once I found the appropriate page of documentation, I did a search for “Defining Default Values,” and the 1st search result that was returned was under the broad topic of Object-Oriented Programming. This documentation miss-directed me in that the style for setting default values in the world of OOP is different than the world of Handle Graphics.

Let me turn this around a bit: List the series of documentation that I needed to read so I could have learned all I needed to know to generate your above command just from reading the documentation.

By the way, this encounter with the non-FRP documentation took me to the nice hot-link populated tree discussing Handle Graphic Object Properties. This section of documentation illustrates very strongly the shortcoming & complexity of MatLab’s graphic process.

Loren replied on : 39 of 45

OysterEngineer-

The setting of defaults is documented in one place for all of graphics. It’s not specific to any of the graphics primitives, but appropriate for all of them. I’m guessing the thinking was that it would bloat the documentation to mention setting different defaults in each FRP. But I will pass along your thoughts on this.

O is indeed the root level.

Thanks for your thoughtful comments on the documentation. Again, I will pass them along.

–Loren

Les replied on : 40 of 45

One of the main things I use startup.m for is to turn on grid lines by default. As another poster commented: why isn’t this the default (or at least an option configurable without having to put these commands in the startup.m script)?

I also use it to set the MATLABROOT environment variable to correspond to the version of Matlab that has just been invoked.

I use this environment variable in Makefiles for S-function builds. This allows using the same Makefile for use with multiple Matlab versions without manual editing of the Makefile.

This requires the use of the setx utility from Microsoft’s “Windows XP Service Pack 2 Support Tools” which allows setting system environment variables. The support tools pack can be downloaded from:

Here is the operative portion of my startup.m:

% Turn grid lines on by default
set(0, 'defaultAxesXGrid', 'on')
set(0, 'defaultAxesYGrid', 'on')
set(0, 'defaultAxesZGrid', 'on')

% Set the MATLABROOT environment variable if it is not set correctly or
% it does not exist
if (~isequal(getenv('MATLABROOT'), matlabroot))
fprintf('Updating MATLABROOT environment variable\n\n');
result = dos(['setx MATLABROOT "' matlabroot '"']);
if (result ~= 0)
fprintf(['\nError setting MATLABROOT environment variable.  ', ...
'You may not have the setx utility installed.\n'...
'See the help below:\n\n']);
help startup
end
end
clear result


-Les

andreimr replied on : 41 of 45

Thanks to your post, I now use

startup.m

to set up my programming environment. I call EditorMacro.m (available off of mathworks.com> to set up a number of keybindings to matlab scripts that I use as part of my programming workflow. I also CD to the directory of the project I’m working on.

onur replied on : 42 of 45

When I execute a long script from startup.m, it crashes after a while. Why?

It seems like I can’t call a script from startup and have it operational for a long time.

Loren replied on : 43 of 45

Onur-

You should contact technical support and supply with with everything they need to run your script. You can reach support via the link on the right of this blog.

–Loren

Tom replied on : 44 of 45

my startup.m contains:

disp('Loading Previous Workspace...')


I then have a corresponding finish.m:

disp('Saving Current Workspace...')
save matlab.mat;


This way I have a persistent workspace and can always continue where I left off

Loren replied on : 45 of 45

Thanks for sharing your use, Tom.

–Loren