Matlab Tips and Tricks: Gabriel Peyr e Peyre@cmapx - Polytechnique.fr August 10, 2004
Matlab Tips and Tricks: Gabriel Peyr e Peyre@cmapx - Polytechnique.fr August 10, 2004
Gabriel Peyré
[email protected]
August 10, 2004
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
• Reverse a vector.
x = x(end:-1:1);
1
tic; fft(rand(500)); disp( [’it takes ’ num2str(toc) ’s.’] );
• 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);
2
str = char( zeros(n,1)+’*’ );
3
2 General Mathematical Tips
• Shuffle an array x.
y = x( randperm(length(x)) );
4
% 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;
• 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
• 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;
5
% first solution
x = (abs(x)>=T) .* x;
% second one : nearly 2 times slower
I = find(abs(x)<T); x(I) = 0;
• Keep only the n biggest coefficients of a signal x (set the others to 0).
[,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;
6
• 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));
• 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(:));
• 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) );
• Same but for 2D signals
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
7
curve is assumed in [0, 1]2 )
cs = c*(n-1) + 1; % scale to [1,n]
I = round(cs);
J = sub2ind(size(M), I(1,:),I(2,:) );
y = sum(M(J));
• Draw the image of a disk and a square.
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;
imagesc(D); % a disk
C = max(abs(X-c(1)),abs(Y-c(2)))<r;
imagesc(C); % a square
• Draw 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
z = cos(pi*x) .* cos(pi*y);
tri = delaunay(x,y); % build a Delaunay triangulation
trisurf(tri,x,y,z);
• 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( mean( (x-y).ˆ2 ) );
m = max( max(x(:)),max(y(:)) );
PSNR = 10*log10( m/d );
8
• 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
9
5 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.
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
10