Matlab Tips
Matlab Tips
Matlab Tips
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
1
Reverse a vector.
x = x(end:-1:1);
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
% all the optional arguments are in options
function fun(x,y,options)
arg = getoptions(options, ’arg’, ’default’);
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);
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 size of the line and markers for the plot display.
h = plot(...);
set(h, ’LineWidth’, 2);
set(h, ’MarkerSize’, 10);
2 Input/Output tips
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
5
m = sum(x(:).ˆ2);
Shuffle an array x.
y = x( randperm(length(x)) );
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);
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;
8
5 Signal Processing Tips
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 );
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) );
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
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
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
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) ) );
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 ) );
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;
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
14
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: