MatLab


Basics / General Information

Running matlab on condor: HTCondor page
comment out something: %this is commented out
to comment out an entire section of code: %{ this is commented out %}
run a script not in the matlab path: run('path/example.m')
prepend a path (including subdirectories): addpath(genpath('/archive/home/ethrane/matapps'));
prepending takes precendent over existing paths
prepend an additional path: addpath /ldcg/matlab_r2007a/toolbox/matlab/iofun
find function documentation (e.g., addpath): help addpath
find function (e.g., in the library (e.g., dataread): which dataread
To run MatLab from the command line: matlab < script.m
To carry out a loop:
for ii=1:24
stochastic(paramfile, jobfile, ii);
end
miscellaneous debugging advice:
In at least one case, the solution to this cryptic error message:
  Segmentation violation occurred within signal handler.
was to simply run matlab with the display option on.
set a default value: defval('Nindep',400);
auto-indent: open your .m file in an interactive matlab session.   Select all the text.   Select Text>'Smart Indent'.
inundated with warning messages? type warning off to turn off warning messages
to return the second, third, (etc.) variable from a function without having to define dummy variables (in matlab >=2009):
[~, ind] = sort(X)
To debug with nodisplay:
  dbstop postprocess
  postprocess
  dbstep 98 
The dbstep command here executes the first 98 commands, then stops.
To enter debug mode put the command keyboard into your .m file.
Now you can see the values of variables from the matlab command line.
To exit debug mode type return.
To quit the program without finishing: dbquit
To continue: dbcont
to compile matlab code (from the matlab command line): mcc -m stochastic
to compile with no java, no display, and no multi-threading: mcc -R -nodisplay -R -nojvm -R -singleCompThread -m stochastic
The singleCompThread option can reduce matlab's tendency to request enormous chunks of memory that it doesn't end up using.
to avoid warning messages about figures left open, close all your figures at the end of the function: close all;
to compile with paths not defined in your startup.m file: mcc -v -R -nojvm -I "/home/gstef/matapps/releases/Utilities/current/misc/"
command line arguments are passed as strings:
function stochastic(paramsFile, jobsFile, jobNumber)
  params.jobNumber = strassign(jobNumber);
  if params.jobNumber==0
    return;
  end
...
return
To save all the variables in your current work station into a .mat file: save file.mat
To save just one variable: save('test.mat','CC');
To retrieve them: oldstuff=open('file.mat')
The variable x can be seen by typing: oldstuff.x
Does a variable exist? (Has it been defined?) exist('varb');
what type of variable is it? class(varb)
Delete/remove a file: delete('map_1.mat');
Delete/remove a directory and everything in it (recursive rm): rmdir('.inj/', 's');
Why are some variables passed at the command line corrupted?
Don't forget to do str2num(variable) if it is a number!
There is another handy function called num2str.
shell commands from matlab: !echo "hello"
[status, host] = system('hostname');
shell commands with variables: [status, output] = system(['echo ', variable]);
What is the process ID of my matlab session?
pid = feature('getpid')
This is an undocumented matlab feature.

Manipulating arrays

define a domain over which to calculate something: x=0:.01:5;
x is defined on (0,5) at increments of .01
define vectors as columns of the matrix:
ra=radec(:,1); %first column
dec=radec(:,2); %second column
To view the value of a variable/array just type the variable and hit enter.
To change an array element: numFreqs(1,1)=1;
To view the value of an array buried inside a data structure use a dot: dataSC.data
to flip a matrix upside down: data = flipud(data)
To fill a matlab cell: etparams.parameters(1)={'resolution'};
etparams.parameters(2)={'0.1'};
...in the context of a for-loop: etparams.parameters{jj}=tmp;
To display the contents of an array of char when all you see is, e.g., [1x91 char]: char(inputfile)
converting char to numbers:
[temp setnum]=regexp(matfilename,'SpHSet(.*)\.job.*','match','tokens');
setnum=str2num(char(setnum{1}));
To find an element in an array satisfying a condition: sigmaPix(RA==6&DECL==0)
comparing elements of two arrays of different sizes: sum(ismember(f,g))
convert a 2D array to a 1D array: Q = q(:);
convert a 1D array into a 2D array: psd2D = reshape(psd1D, nfreqs, nsegments);
to make a 2D array that contains many copies of a 1D array:
% s is 8000 x 1 and you want to make it 8000 x 100
T = 100;
q = repmat(s, 1, T);
% s is 1 x 8000 and you want to make it 100 x 8000
q = repmat(s, T, 1);
kron can be used to construct tensor products:
phase_n = kron(ones(length(xpos),1),exp(-2*pi*i*freqs(cut2)*lag));

Plotting

line plot: plot(x,y);
Label axes: xlabel('frequency (Hz)')
Greek letters: xlabel('\mu')
To make a log plot: semilogy(data5(:,3),data5(:,4),'r')
To make a log-log plot: loglog(...)
To change the domain/range of a plot: axis([20 2000 10e-46 10e-43])
This command goes after the plot command.
Bode plot:
delay = tf(num,den);
bode(delay,{10^3,10^5});
scatter plot with the mapping package: scatterm(dec,ra,15,'r','filled')
This command puts a size=15 red dot at every data point in ra,dec space.
superimpose a second dataset with blue dots on top of the existing map: scatterm(decp,rap,15,'b','filled')
To print to an .eps file: print -depsc test.eps;
(The "c" is for color.)
To superimpose two plots: use "hold" as in example_hold.m
Or like this:
  plot(data(:,3),data(:,4),'r',data(:,3),data(:,5),'b');
  legend('real','imaginary');
The figure(H) command makes H the current figure, forces it to become visible, and raises it above all other figures on the screen. If Figure H does not exist and H is an integer, a new figure is created with handle H.
To make a histogram:
f=load('jobs1-5.diff');
hist(f)
subplots:
subplot(2,1,1); plot(x1,y1)
subplot(2,1,2); plot(x2,y2)
pretty.m script to make figure fonts legible
change the font size of everything on the current figure: set(gca,'FontSize',20);
then:
h_xlabel = get(gca,'XLabel');
set(h_xlabel,'FontSize',20);
change the marker size on scatter plots:
qq1=scatter(...
qq1Child=get(qq1,'Children');
set(qq1Child,'MarkerSize',8);
change the marker size on errorbar plots:
qq2=errorbar(...
set(qq2,'MarkerSize',13);
set(qq3,'MarkerSize',13);
contour plots with a log axis:
[C, h] = contour(A_ii, alpha_jj, z, zcontours);
x1 = C(1, 2:end);
y1 = C(2, 2:end);
semilogx(x1, y1, 'b', 'linewidth', 2);
To make a legend for only some curves on your plot:
h1 = plot(x1, y1)
...
legend([h1 h2 h3], 'stoch', 'CBC', 'combined', 'true');
colors
% pink
R2=loglog(sn.freqs, sn.ul0);
set(R2,'Color',[1,0.4,0.6]);
% purple
Q2=loglog(sn.freqs, sn.h_sig);
set(Q2,'Color',[0.5,0,0.5]);
Set tick marks manually: set(gca, 'YTick', [1e-7 1e-5 1e-3]);
Plotting two y-axes at the same time with different units (only works for eps printed with matlab_r2013a:
% use matlab 2014
[ax, h] = plot2axes(@loglog, f, r, 'yscale', (4000/1e-12));
fs = 16;
ylabel(ax(1), 'strain/pT', 'FontSize', fs);
ylabel(ax(2), 'm/T', 'FontSize', fs);
xlabel('f (Hz)', 'FontSize', fs);
set(gca, 'FontSize', fs);
grid on;
print('-dpng', 'coupling');

Input/output

read in data from a text file: load file.dat
The data will be stored in a matrix called "file".
or: data=load('file.dat')
then make a plot from data in a file: plot(data(:,3),data(:,4))
Read in strings/text: files=textread(filelist,'%s');
to print to screen: fprintf('cet: E this is a test\n');
to read in an arbitrary (unformatted) text file: read_doc To save array variables as columns of ascii text:
out = [t hp hx];
save('wave_inj.dat', 'out', '-ASCII');
or to save a large char to file:
fid=fopen('.inj/inj_params.txt','w+');
fprintf(fid, '%c', out);
fclose(fid);
To print variables to screen: fprintf(1,'-------> %f \n',jobNumber);
1 is for std:out, 2 is for std:err, or to...
write to a file:
fid=fopen('file.out','w+');
fprintf(fid,'%f \n',jobNumber);
fclose(fid)
to print in scientific notation: fprintf(fid, '%f %e %e\n', tt(ii), HP(ii), HX(ii));
to print a fixed number of significant figures: fprintf('%5.2g\n', fluence)
To get more precise numerical output from matlab: format long
Get a list of all the .mat files in a directory: tmp = dir('week1/coherence_data*.mat')
This will return an array tmp with N entires, one for each .mat file matching the regular expression. The name of the 13th file in this array is: tmp(13).name

Manipulating strings and other text

compare two strings: TF = strcmp('str1', 'str2');
Matlab regular expressions (replacement): regexprep(g,'txt','mat');
Matlab regulgar expressions:
filename = '/data/node3/ethrane/file.mat';
[temp2 node] = regexp(filename,'/data/node(.).*','match','tokens');
parsing space- or tab- delimited data: trigdata = regexp(str,' ','split');
add current date and time to a plot: title(['(' datestr(now) ')']);

Functions

define a mathematical function: f=@(x) x^2;



Random numbers

random seeding: randn('state', sum(100*clock))
  • note: rand and randn are seeded separately.
  • note: randn('state',x) will set the same seed for any value of x≥2^32 ~ 4.3e9 so make sure you do not set the seed value to be too large!
  • For each seed value, the Mersenne Twister algorithm used by matlab, will generate ~2^19937 random numbers before repeating.
  • more on random numbers using matlab
    a cool randomizing feature with matlab: randperm



    Fourier transforms

    matlab fft tutorial
    fft_eht.m: a function to keep track of frequency bins when Fourier transforming time-series data.
    ifft_eht.m: a function to keep track of frequency bins when inverse Fourier transforming
    noise_gen.m: a function to generate colored noise
    cal_fluence.m: a function go calculate GW fluence from a time series; also demonstrates Parseval's theorem (if you comment out a few lines of code).



    Common calculations

    calculate the probability of getting max(SNR) >ρ given T trials and assuming norally-distributed variables: probmax.m
    simulated colored Gaussian noise: gaussian_noise.m
    use mod to ensure some variable x is defined on [1,N]: mod(x-1, N) + 1



    Profiling matlab code

    Note: matlab has to be running with the GUI on or there may be java errors! The matlab profile option allows you to make html documentation of a matlab function. The documentation shows which functions were called, how long they took to run and other information. The functions are linked together with hypertext. This is a really convenient way to review/optimize/debug code. Here are the instructions.
  • open matlab
  • >> profile on
  • >> run_stochmap_ex1; % run the code you want to profile
  • >> p = profile('info');
  • >> profsave(p,'profile_results')
    These commands will create a directory called profile_results/ filled with html files of the form file#.html. Begin by opening file0.html. In our example, this will correspond to the main function, run_stochmap.m. Now you can step through each subroutine by following the hyperlinks from file0.html.

    Back to Resources