Sunday, December 12, 2010

More fun with matrices

I'm more impressed with Matlab and Octave.

Octave (Matlab also) has a small language that lets one build scripts. This language has two features that give Octave (and Matlab) its advantages.

The first feature is parallel assignment. Programming languages have had serial assignment since the early days of COBOL and FORTRAN. Serial assignment moves one item in a statement, like BASIC's

LET A = B + C

It is a simple operation, easy to program and easy to understand.

Parallel assignment moves multiple items in one statement. Perl has it, and the typical example is

($a, $b) = ($b, $a);

to swap to values. The corresponding code with serial assignment is:

temp = a;
a = b;
b = temp;

Notice that one line of parallel assignment requires three lines (and an extra variable) in serial assignment.

(Actually, COBOL had a sophisticated "MOVE CORRESPONDING" operation that is rarely discussed. It moved one record to another record of a different structure, moving fields based on their names, which meant that COBOL "did the right thing", all in one line.)

The second feature is the colon operator, which generates a sequence of numbers. The expression "1:10" generates a list of numbers from 1 to 10. A variant on the syntax allows you to specify the interval size, so the expression "1:0.5:10" generates the numbers from 1 to 10 in steps of 0.5 in size.

An expression that generates a list is more powerful than one might think. After all, you can generate a sequence of numbers in a loop and every programming language has basic looping. But the expression that generates a list is a compact thing, roughly the equivalent to C's pointer arithmetic. Just as C can use pointer arithmetic for

while (*d++ = *s++);

Octave can use the colon operator for

list = 1:7:365;

for a list of numbers that might represent days in the year.

Combining parallel assignment with the colon operator provides for some powerful programming constructs. Where in other languages we would need to set up loops and control variables, in Octave we can perform a single operation:

output(10:20) = data(1:11);

This moves eleven items from 'data' into 'output'. Without parallel assignment and the list generator, we would need:

for (int i = 10; i <= 20; i++)
output(i) = data(i - 9);

Now, one might argue that the difference between these two code snippets is small, with the difference being one line of code and the latter using familiar constructs. Yet I find the Octave version much easier to read -- once I learned the 'lingo' of Octave.

And programs that are easier to read are easier to write, easier to understand, and easier to debug.

So I'm impressed with Octave.

No comments:

Post a Comment