Matlab snippet: calculate Euclidean transformation

Nothing special really but since I have to do a lot of things in Matlab these days, why not post some snippets in case anyone will need something like this and decides to search the Net for it.

This function should calculate Euclidean transformation in 2D ... you know ... the translation and rotation thing. If I have done something wrong or it could be done better please let me know ... it was done in a hurry and I have to learn somehow :)

#!matlab
% Calculates 2D Euclidean transform (just translation and rotation)
%
% Input parameters: P1 - first set of points (nx2)
%                   P2 - second set of points (nx2)
%
% Output: T - 3x3 transformation matrix
%
function [T] = euclidean(P1, P2)

% take the minimum amount of available points
p = min([size(P1, 1), size(P2, 1)]);

if (p < 2)
    error('At least two points required.');
end;

A = zeros(2*p, 4);
b = zeros(2*p, 1);

for i = 1:p
    A(i*2-1, :) = [P1(i, 1), -P1(i, 2), 1, 0];
    A(i*2, :) = [P1(i, 2), P1(i, 1), 0, 1];
    b(i*2-1) = P2(i, 1);
    b(i*2) = P2(i, 2);
end;

% solve system
x = A\b;

% build the transformation matrix
T = [x(1) -x(2) x(3); x(2) x(1) x(4); 0 0 1];
Written on Dec. 9, 2008 at 2:21 p.m.
blog comments powered by Disqus