Johannes' Matlab tips

Here are a collection of Matlab tips and tricks that I have learned during my time working with Matlab.

How to make a line plot in arbitrary color?

r = 0; g = 0.6; b = 1; x = 0:0.1:10;
y = sin(x);
plot(x,y,'Color',[r g b]);

How to run a matlab script remotely on linux?

Log on to your favourite linux computer. The first line creates an empty file, the second line runs 1+1 in matlab, you can easilly exchange that for your own script. The output is written to output.txt. You can then close the terminal and the job will continue. The keyword nice lowers the priority of the thread, allowing others to also use the computer if it is a very cpu intensive job.

touch infile.txt
nice matlab -nojvm -nosplash -r "1+1,quit" < infile.txt &> outfile.txt

(this should be just two lines)

How do I tile a matrix?

A = rand(2,1);
repmat(A, 2, 4)

How do I create a block diagonal matrix?

blkdiag(ones(2,2), [1 2; 3 4; 5 6])

What is the kronecker tensor product?

kron(1:4, [1 1 1])
Result: 1 1 1 2 2 2 3 3 3 4 4 4

How do I store vectors of different length?

Use a cell array!
for i = 1:5
  x{i} = rand(1,i);

How do I convert a matrix to a vector?
From: Malin Sandström


How do I reverse a vector?
From: Malin Sandström


Alternatively you can use the command flipdim

How do I merge two fig-files in matlab?
How do I get the coordinates from a curve in a plot?

First get the children of the current figure, then the children of that one. Using that handle you can then extract the X and Y coordinates.

h = get(gcf, 'children')
p = get(h, 'children')
x = get(p, 'XData')
y = get(p, 'YData')

How do I get overlaying plots with different scales on the right and the left Y-axis?
From: Emma Eklöf

% To plot the two data sets
[ax, h1, h2] = plotyy(x1,y1,x2,y2);
% Sets the label on the x axis
xlabel('Label x');
% Sets the label on the left y axis
ylabel('Label 1');
% Changes the active axis to the 2nd axis
% Put label on the right axis ylabel('Label 2');

How do I set the axis ticks?
From: Mia

Example of how to do it

How do I make a grid where each pixel has different colors?
From: Mia

[x,y] = meshgrid(1:10,1:10);
z = rand(size(x));

I want the same axis on all my subplots!

ax(1) = subplot(2,2,1); plot(rand(1,10)*10,'Parent',ax(1)); ax(2) = subplot(2,2,2); plot(rand(1,10)*100,'Parent',ax(2)); linkaxes(ax,'x');
Example from matlab help.

How do I plot without X-windows?

Create an invisible figure, plot, and save it to a file as usual.

p = figure('Visible', 'off')

How do I increase the xlabel fontsize from a script


How do I plot an inset figure in matlab?

% First plot what you want in figure
plot(1:5,sin(1:5)), box off
% Here we specify x,y,height,width of inset
axes('pos',[0.5 0.6 0.4 0.3]);
% Now plot inset
plot(1:6,cos(1:6)), box off

Return to Main Page