Matlab Tips

Download as pdf or txt
Download as pdf or txt
You are on page 1of 14

Matlab Tips and Tricks

Gabriel Peyré
CEREMADE, Université Paris Dauphine
gabriel.peyre@ceremade.dauphine.fr
November 18, 2007

First keep in mind that this is not a Matlab tutorial. This is just a list of
tricks I have found useful while writing my toolboxes available on the Matlab
Central repository
http://www.mathworks.com/matlabcentral/
You can e-mail me if you have corrections about these pieces of code, or if you
would like to add your own tips to those described in this document.

Contents
1 General Programming Tips 1

2 Input/Output tips 4

3 General Mathematical Tips 5

4 Advanced Mathematical Tips 6

5 Signal Processing Tips 9

6 Image Processing Tips 10

7 Graph Theory Tips 13

8 Wavelets and Multiresolution Tips 14

1 General Programming Tips

Suppress entries in a vector.


x( 3:5 ) = [];

1
Reverse a vector.
x = x(end:-1:1);

Use cell arrays to store stuff of various types.


x = {}; x{end+1} = 1; x{end+1} = [1 2]; % build incrementally
x = {x{end:-1:1}}; % reverse the same way as a vector

Compute the running time of a function call.


tic; fft(rand(500)); disp( [’it takes ’ num2str(toc) ’s.’] );

Make a array full of NaN


% guess which one is the fastest ?
tic; NaN*ones(2000,2000); toc;
tic; repmat(NaN,2000,2000); toc;

Turn an nD array into a vector.


x = x(:);

Compute the maximum value of an nD array.


m = max(x(:));

Access a matrix from a list of entries. Here, we have I = [I1; I2] and y(i)
= M( I1(i), I2(i) )
J = sub2ind(size(M), I(1,:),I(2,:) );
y = M(J);

Create a function that take optional arguments in a struct.


function y = f(x,options)
% parse the struct
if nargin<2
options.null = 0; % force creation of options
end
if isfield(options, ’a’)
options.a = 1; % default value
end
a = options.a;
if isfield(options, ’b’)
options.b = 1; % default value
end
b = options.b;
% Here the body of the function ...

A cleaner way to manage an options data structure is to define a function to do


the job.

2
% all the optional arguments are in options
function fun(x,y,options)
arg = getoptions(options, ’arg’, ’default’);

% here is the definition of the function


function v = getoptions(options, name, v, mendatory);
if isfield(options, name)
v = eval([’options.’ name ’;’]);
end

How to duplicate a character n times.


str = char( zeros(n,1)+’*’ );

Assign value v in a nD array at a position ind (lenth-n vector).


ind = num2cell(ind);
x( ind{:} ) = v; % the comma-separated trick

Write a function fun(a,b,c) that can takes an arbitrary number of arguments.

% first method, simple but long


function fun(a,b,c)
if nargin<1
a = 0.1246;
end
if nargin<2
b = 1.2346;
end
if nargin<3
c = 8.7643;
end
% second method, much more elegant
function fun(args)
default values = {0.1246,1.2346,8.7643};
args present = cellfun(isempty,args);
default values(args presen) = args(args present);
[a b c] = deal(default values:);

Remove the ticks from a drawing.


set(gca, ’XTick’, []);
set(gca, ’YTick’, []);

Find the angle that makes a 2D vector x with the vector [1,0]
% just the angle
theta = atan2(x(2),x(1));
% if you want to compute the full polar decomposition
[theta,r] = cart2pol(x);

Try to allocate memory before adding new data to an array

3
n = 10000; a = [];
tic;
for i=1:n
a(i) = 1; % this will reallocate size
end
toc; tic;
for i=1:n
a(i) = 1;
end
toc; % should be 15 times faster

Enlarging the font for the plot display.


set(0,’defaultaxesfontsize’,14,’defaultaxeslinewidth’,0.9,...
’defaultlinelinewidth’,1,’defaultpatchlinewidth’,0.9);

Enlarging the size of the line and markers for the plot display.
h = plot(...);
set(h, ’LineWidth’, 2);
set(h, ’MarkerSize’, 10);

2 Input/Output tips

Create a graphical waitbar.


n = 100;
h = waitbar(0,’Waiting ...’);
for i=1:n
waitbar(i/n);
% here perform some stuff
end
close(h);

Output a string without carriage return.


fprintf(’Some Text’);

Saving and loading an image.


% saving current display
saveas(gcf, ’my image’, ’png’);
% saving a 2D or 3D matrix into an image
imwrite(M, ’my image’, ’png’); % M should have its values in [0,1]
% loading into a 2D (gray) or 3D (color) matrix
M = double( imread( ’my image.png’ ) );

Saving and loading a matrix M in a binary file.

4
[n,p] = size(M); % saving
str = ’my file’; % name of the file
fid = fopen(str,’wb’);
if fid<0
error([’error writing to file ’, str]);
end
fwrite(fid,M’,’double’); % store it row-wise format
fclose(fid);
% loading
fid = fopen(str,’rb’);
if fid<0
error([’error reading file ’,str]);
end
[M, cnt] = fread(fid,[n,p],’double’); M = M’;
fclose(fid);
if cnt =n*p
error([’Error reading file ’, str]);
end

Writing/Reading to a text file a list of 3-uplets.


% A is a matrix with 3 rows.
fid = fopen(filename,’wt’);
fprintf(fid, ’%f %f %f\n’, A);
fclose(fid); % Retrieving the values back from file to matrix B.
fid = fopen(filename,’r’);
[B,cnt] = fscanf(fid,’%f %f %f’);

Building an AVI file.


mov = avifile(’filename’);
for i=1:nbrframes
% draw some stuff here
F = getframe(gca);
mov = addframe(mov,F);
end
mov = close(mov);

3 General Mathematical Tips

Rescale the entries of a vector x so that it spans [0, 1]


m = min(x(:)); M = max(x(:));
x = (b-a) * (x-m)/(M-m) + a;

Generate n points evenly sampled.


x = 0:1/(n-1):1; % faster than linspace

Compute the L2 squared norm of a vector or matrix x.

5
m = sum(x(:).ˆ2);

Subsample a vector x or an image M by a factor 2.


x = x(1:2:end); % useful for wavelet transform
M = M(1:2:end,1:2:end);

Compute centered finite differences.


D1 = [x(2:end),x(end)];
D2 = [x(1),x(1:end-1)];
y = (D1-D2)/2;

Compute the prime number just before n


n = 150;
P = primes(n); n = P(end);

Compute J, the reverse of a permutation I, i.e. an array which contains the


number 1:n in arbitrary order.
J(I) = 1:length(I);

Shuffle an array x.
y = x( randperm(length(x)) );

4 Advanced Mathematical Tips

Generate n points x sampled uniformly at random on a sphere.


% tensor product gaussian is isotropic
x = randn(3,n);
d = sqrt( x(1,:).ˆ2+x(2,:).ˆ2+x(2,:).ˆ2 );
x(1,:) = x(1,:)./d;
x(2,:) = x(2,:)./d;
x(3,:) = x(3,:)./d;

Create a random vector x with s non-zero entry (s-sparse vector)


sel = randperm(n); sel = sel(1:s);
x = zeros(n,1); x(sel) = 1;

Construct a polygon x whose ith sidelength is s(i). Here x(i) is the complex
affix of the ith vertex.
theta = [0;cumsum(s)];
theta = theta/theta(end);
theta = theta(1:(end-1));
x = exp(2i*pi*theta);
L = abs(x(1)-x(2));
x = x*s(1)/L; % rescale the result

6
Compute y, the inverse of an integer x modulo a prime p.
% use Bezout thm
[u,y,d] = gcd(x,p);
y = mod(y,p);

Compute the curvilinear abscise s of a curve c. Here, c(:,i) is the ith point
of the curve.
D = c(:,2:end)-c(:,1:(end-1));
s = zeros(size(c,2),1);
s(2:end) = sqrt( D(1,:).ˆ2 + D(2,:).ˆ2 );
s = cumsum(s);

Compute the 3D rotation matrix M around an axis v


% taken from the OpenGL red book
v = v/norm(v,’fro’);
S = [0 -v(3) v(2); v(3) 0 -v(1); -v(2) v(1) 0];
M = v*transp(v) + cos(alpha)*(eye(3) - v*transp(v)) + sin(alpha)*S;

Compute a VanderMonde matrix M i.e. M(i,j)=x(i)ˆj for j=0:d.


n = length(x); % first method
[J,I] = meshgrid(0:d,1:n);
A = x(I).ˆJ;
% second method, less elegant but faster
A = ones(n);
for j = 2:n
A(:,j) = x.*A(:,j-1);
end

Threshold (i.e. set to 0) the entries below T.


% first solution
x = (abs(x)>=T) .* x;
% second one : nearly 2 times slower
I = find(abs(x)<T); x(I) = 0;

Same, but with soft-thresholding


s = abs(x) - t;
s = (s + abs(s))/2;
y = sign(x).*s;

Projection of a vector x on the `1 ball {y;


P
i |y(i)| = λ}.

7
% compute the thresholded L1 norm at each sampled value
s0 = sort( abs(x(:)) );
s = cumsum( s0(end:-1:1) ); s = s(end:-1:1);
s = s - s0 .* (length(x(:)):-1:1)’;
% compute the optimal threshold by interpolation
[i,tmp] = max( find(s>lambda) );
if isempty(i)
y = x; return;
end
i = i(end);
t = ( s(i+1)-lambda )/( s(i+1)-s(i) ) * (s0(i)-s0(i+1)) + s0(i+1);
% do the actual thresholding
y = x; y(abs(x)<t) = 0;
y(abs(x)>=t) = y(abs(x)>=t) - sign(x(abs(x)>=t))*t;

Keep only the n biggest coefficients of a signal x (set the others to 0).
[tmp,I] = sort(abs(x(:))); x( I(1:end-n) ) = 0;

Draw a 3D sphere.
p = 20; % precision
t = 0:1/(p-1):1;
[th,ph] = meshgrid( t*pi,t*2*pi );
x = cos(th);
y = sin(th).*cos(ph);
z = sin(th).*sin(ph);
surf(x,y,z, z.*0);
% some pretty rendering options
shading interp; lighting gouraud;
camlight infinite; axis square; axis off;

Project 3D points on a 2D plane (best fit plane). P(:,k) is the kth point.
for i=1:3 % substract mean
P(i,:) = P(i,:) - mean(P(i,:));
end
C = P*P’; % covariance matrix
% project on the two most important eigenvectors
[V,D] = eigs(C);
Q = V(:,1:2)’*P;

Compute the pairwise distance matrix D between a set of p points in Rd . Here,


X(:,i) is the ith point.
X2 = sum(X.ˆ2,1); D = repmat(X2,p,1) + repmat(X2’,1,p)-2*X’*X;

Orthogonalize a matrix A by projection on the set of orthogonal matrix (not


Gram-Schmidt)
[U,D,V] = svd(A); A = U*V’;

8
5 Signal Processing Tips

Compute circular convolution of x and y.


% use the Fourier convolution thm
z = real( ifft( fft(x).*fft(y) ) );

Build a 1D gaussian filter of variance s.


x = -1/2:1/(n-1):1/2;
f = exp( -(x.ˆ2)/(2*sˆ2) );
f = f / sum(sum(f));

Perform a 1D convolution of signal f and filter h with symmetric boundary


conditions. The center of the filter is 0 for odd length filter, and 1/2 otherwise
n = length(x); p = length(h);
if mod(p,2)==1
d1 = (p-1)/2; d2 = (p-1)/2;
else
d1 = p/2-1; d2 = p/2;
end
xx = [ x(d1:-1:1); x; x(end:-1:end-d2+1) ];
y = conv(xx,h);
y = y( (2*d1+1):(2*d1+n) );

Generate a signal whose regularity is C α (Sobolev).


alpha = 2; n = 100;
y = randn(n,1); % gaussian noise
fy = fft(y);
fy = fftshift(fy);
% filter the noise with |omega|ˆ-alpha
h = (-n/2+1):(n/2);
h = (abs(h)+1).ˆ(-alpha-0.5);
fy = fy.*h’;
fy = fftshift(fy);
y = real( ifft(fy) );
y = (y-min(y))/(max(y)-min(y));

Generate a signal whose regularity is nearly C α−1/2 .


alpha = 3; n = 300;
x = rand(n,1); % uniform noise
for i=1:alpha % integrate the noise alpha times
x = cumsum(x - mean(x));
end

Compute the PSNR between to signals x and y.


d = mean( (x(:)-y(:)).ˆ2 );
m = max( max(x(:)),max(y(:)) );
PSNR = 10*log10( m/d );

9
Evaluate a cubic spline at value t (can be a vector).
x = abs(t) ;
I12 = (x>1)&(x<=2); I01 = (x<=1);
y = I01.*( 2/3-x.ˆ2.*(1-x/2) ) + I12.*( 1/6*(2-x).ˆ3 );

Perform spectral interpolation of a signal x (aka Fourier zero-padding). The


original size is n and the final size is p
n = length(x); n0 = (n-1)/2;
f = fft(x); % forward transform
f = p/n*[f(1:n0+1); zeros(p-n,1); f(n0+2:n)];
x = real( ifft(f) ); % backward transform

Compute the approximation error err= ||f − fM ||/||f || obtained when keeping
the M best coefficients in an orthogonal basis.
% as an example we take the decomposition in the cosine basis
M = 500;
x = peaks(128); y = dct(x); % a sample function
[tmp,I] = sort(abs(y(:)));
y(I(1:end-M)) = 0;
err = norm(y,’fro’)/norm(x,’fro’); % the relative error
xx = idct(y); imagesc(xx); % the reconstructed function

Evaluate the number of bits needed to code a vector v with arithmetic coding.
h = hist(v,100); % use 100 bins for histogram
% use Shannon’s upper bound
nbr bits = - length(v(:)) * sum( h.*log2(h) );

Perform the histogram equalization of a vector x so that it matches the his-


togram of another vector y.
[vx,Ix] = sort(x); [vy,Iy] = sort(y);
nx = length(x); ny = length(y);
ax = linspace(1,ny,nx); ay = 1:ny;
vx = interp1(ay,vy,ax);
x(Ix) = vx;

6 Image Processing Tips

Display the result of an FFT with the 0 frequency in the middle.


x = peaks(256);
imagesc( real( fftshift( fft2(x) ) ) );

Resize an image M (new size is (p1,q1)).

10
[p,q] = size(M); % the original image
[X,Y] = meshgrid( (0:p-1)/(p-1), (0:q-1)/(q-1) );
% new sampling location
[XI,YI] = meshgrid( (0:p1-1)/(p1-1) , (0:q1-1)/(q1-1) );
M1 = interp2( X,Y, M, XI,YI ,’cubic’); % the new image

Build a 2D gaussian filter of variance s.


x = -1/2:1/(n-1):1/2;
[Y,X] = meshgrid(x,x);
f = exp( -(X.ˆ2+Y.ˆ2)/(2*sˆ2) );
f = f / sum(f(:));

Image convolution with centered filter


n = length(x); p = length(h);
if mod(p,2)==1
d1 = (p-1)/2; d2 = (p-1)/2;
else
d1 = p/2-1; d2 = p/2;
end
xx = [ x(d1:-1:1,:); x; x(end:-1:end-d2+1,:) ];
xx = [ xx(:,d1:-1:1), xx, xx(:,end:-1:end-d2+1) ];
y = conv2(xx,h);
y = y( (2*d1+1):(2*d1+n), (2*d1+1):(2*d1+n) );

Extract all 0th level curves from an image M an put these curves into a cell array
c list.
c = contourc(M,[0,0]);
k = 0; p = 1;
while p < size(c, 2) % parse the result
lc = c(2,p); % length of the curve
cc = c(:,(p+1):(p+lc));
p = p+lc+1;
k = k+1;
c list{k} = cc;
end

Quick computation of the integral y of an image M along a 2D curve c (the


curve is assumed in [0, 1]2 )
cs = c*(n-1) + 1; % scale to [1,n]
I = round(cs);
Draw the image of a disk
J = sub2ind(size(M), I(1,:),I(2,:) );
y = sum(M(J));

and a square.

11
n = 100; x = -1:2/(n-1):1;
[Y,X] = meshgrid(x,x);
c = [0,0]; r = 0.4; % center and radius of the disk
D = (X-c(1)).ˆ2 + (Y-c(2)).ˆ2 < rˆ2; Draw
imagesc(D); % a disk
C = max(abs(X-c(1)),abs(Y-c(2)))<r;
imagesc(C); % a square

a 2D function whose value z is known only at scattered 2D points (x,y).


n = 400;
x = rand(n,1); y = rand(n,1);
% this is an example of surface
Generate
z = cos(pi*x) .* cos(pi*y);
tri = delaunay(x,y); % build a Delaunay triangulation
trisurf(tri,x,y,z);

c(ω) = ω −α .
a noisy cloud-like image M whose Fourier spectrum amplitude is M

x = -n/2:n/2-1;
[Y,X] = meshgrid(x,x);
d = sqrt(X.ˆ2 + Y.ˆ2) + 0.1;
f = rand(n)*2*pi;
M = (d.ˆ(-alpha)) .* exp(f*1i);
M = real( ifft2( ifftshift(M) ) );

Perform a JPEG-like transform of an image x (replace dct by idct to compute


the inverse transform).
bs = 8; % size of the blocks
n = size(x,1); y = zeros(n,n);
nb = n/bs; % n must be a multiple of bs
for i=1:nb
for j=1:nb
xsel = ((i-1)*bs+1):(i*bs);
ysel = ((j-1)*bs+1):(j*bs);
y(xsel,ysel) = dct(x(xsel,ysel));
end
end

Extract interactively a part MM of an image M.


[n,p] = size(M);
imagesc(M);
axis image; axis off;
sp = getrect;
sp(1) = max(floor(sp(1)),1); % xmin
sp(2) = max(floor(sp(2)),1); % ymin
sp(3) = min(ceil(sp(1)+sp(3)),p); % xmax
sp(4) = min(ceil(sp(2)+sp(4)),n); % ymax
MM = M(sp(2):sp(4), sp(1):sp(3));

12
Compute the boundary points of a shape represented as a binary image M.
M1 = conv2(M,ones(3)/9, ’same’);
% A indicates with 1 the location of the boundary A = Mh>0 & Mh<9 & M==1;
I = find(A); % index of the boundary
[x,y] = ind2sub(size(A),I);
plot(x,y); % display the boundary

Solve the Poisson equation ∆G =div(f ) where div(f ) is stored in image d and
G in image G.
% Compute the Laplacian filter in Fourier [Y,X] = meshgrid(0:n-1,0:n-1);
mu = sin(X*pi/n).ˆ2; mu = -4*( mu+mu’ );
mu(1) = 1; % avoid division by 0
% Inverse the Laplacian convolution
G = fft2(d) ./ mu; G(1) = 0;
G = real( ifft2( G ) );

Extract all the w × w patches with a spacing q from an image M


[Y,X] = meshgrid(1:q:n-w, 1:q:n-w); p = size(X,1);
[dY,dX] = meshgrid(0:w-1,0:w-1);
Xp = repmat( reshape(X,[1,1,p]) ,[w w 1]) + repmat(dX,[1 1 p]);
Yp = repmat( reshape(Y,[1,1,p]) ,[w w 1]) + repmat(dY,[1 1 p]);
I = sub2ind([n n], Xp,Yp);
H = M(I);

Compute the correlation between two images A and B of same size


n = size(A,1); sel = [1 n:-1:2];
C = ifft2( fft2(A).*fft2( B(sel,sel) ) );
C1 = ifft2( fft2(B).*fft2( A(sel,sel) ) );
C = real( (C1+C)/2 );

7 Graph Theory Tips

Compute the shortest distance between all pair of nodes (D is the weighted
adjacency matrix).
% non connected vectices must have Inf value
N = length(D);
for k=1:N
D = min(D,repmat(D(:,k),[1 N])+repmat(D(k,:),[N 1]));
end
D1 = D;

Turn a triangulation into an adjacency matrix.

13
nvert = max(max(face));
nface = length(face);
A = zeros(nvert);
for i=1:nface
A(face(i,1),face(i,2)) = 1; A(face(i,2),face(i,3)) = 1;
A(face(i,3),face(i,1)) = 1;
% make sure that all edges are symmetric
A(face(i,2),face(i,1)) = 1; A(face(i,3),face(i,2)) = 1;
A(face(i,1),face(i,3)) = 1;
end

8 Wavelets and Multiresolution Tips

Compute a 2D Haar transform of an image x


if dir==1
for j=Jmax:-1:Jmin
sel = 1:2ˆ(j+1);
x(sel,sel) = fwd step(x(sel,sel));
x(sel,sel) = fwd step(x(sel,sel)’)’;
end
y = x;
else
for j=Jmin:Jmax
sel = 1:2ˆ(j+1);
x(sel,sel) = bwd step(x(sel,sel)’)’;
x(sel,sel) = bwd step(x(sel,sel));
end
y = x;
end

function M1 = fwd step(M)


C = M(1:2:end,:); D = M(2:2:end,:);
M1 = [(C+D)/sqrt(2); (C-D)/sqrt(2)];

function M1 = bwd step(M)


C = M(1:end/2,:); D = M(end/2+1:end,:);
M1 = M; M1(1:2:end,:) = (C+D)/sqrt(2);
M1(2:2:end,:) = (C-D)/sqrt(2);

14

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy