Thursday, May 28, 2009

MATLAB: Spline My Monogram

I saw that exercise as an assignment for a MATLAB course and it reminded me of my senior year in college studying aerospace engineering. As a senior project me and 3 other people designed and build and aeroplane (great fun!) and among other things I used a plastic spline and some weights called ‘ducks’ (to set the curvature). Much easier to do generate splines with a computer!

The code to generate cubic splines is well known and makes use of a tridiagonal system of matrices which lends itself well to MATLAB programming. However, the MATLAB people have made available standard spline functions (also exotic versions for a friendly fee!) which makes the whole operation pretty straight forward. See below; All code is entered in the MATLAB command window.

I first wrote my monogram on an 8x10 engineering paper and determined the (x, y) coordinate pairs (my ducks!) See plot below for my data set. (Set axis to equal for proper appearance.)

>> M = load('monogram data.txt');

>> x = M(:,1);
>> y = M(:,2);

>> plot(x, y, 'o', 'markersize', 5)
>> grid on
>> axis equal

step1_data

If the MATLAB Spline toolbox is available then the function SPCRV will work well.

>> values = spcrv(M,2); % 2nd order

>> subplot(121)
>> plot(x, y, '.b', values(:,1), values(:,2), '-r', 'linewidth', 1)
>> grid on
>> axis equal

>> subplot(122)
>> plot(values(:,1), values(:,2), '-r', 'linewidth', 1)
>> axis equal

step2_spcrv

It is almost as easy to generate the spline using the standard 3rd order SPLINE function available with basic MATLAB. I need to define common parameter t so x(t) and y(t) can be found.

>> n = size(M,1); % number of data points

>> t = 1:n;

>> ts = 1:1:n;

>> xs = spline(t,x,ts);
>> ys = spline(t,y,ts);

>> subplot(121)
>> plot(x, y, '.b', xs, ys, '-g', 'linewidth', 1)
>> grid on
>> axis equal

>> subplot(122)
>> plot(xs, ys, '-g', 'linewidth', 1)
>> axis equal

step3_spline

Compare the two solutions (spcrv vs. spline); The two curves are identical.

step4_compare

Reduce the step size of parameter ts to improve appearance of my monogram.

ts = 1:1/20:n;

xs_ = spline(t,x,ts);
ys_ = spline(t,y,ts);

subplot(121)
plot(x, y, '.b', xs_, ys_, '-g', 'linewidth', 1)
grid on
axis equal

subplot(122)
plot(xs_, ys_, '-c', 'linewidth', 1)
axis equal

 

step5_splineFine

Looks pretty nice!

Now I just have to create my own code (as I have done years ago in FORTRAN) and compare with the MATLAB result. Another day maybe!

No comments:

Post a Comment