JSL Tip: Use Matrices Instead of Lists

The list is one of the basic building tools for organizing data in JSL. The power of lists is that they can contain any kind of items (numbers, characters, other lists, ...), and they can grow and shrink as needed. However, if you just need a fixed list of numbers, you can get much better performance from a one-dimensional matrix.

Consider these two samples that make arrays of odd numbers.

// make a list of odd numbers

n = 1000;

y = {};

for (i = 1, i <= n, i++,

y* = 2 * i - 1;*

);

y;

// make a matrix of odd numbers

n = 1000;

y = J(1, n); // creates a 1 x n matrix with all values set to 1

for (i = 1, i <= n, i++,

y* = 2 * i - 1;*

);

For a few hundred items, there's not much difference. But as n goes beyond 1000 (or if the above code is in a loop), you start to notice the difference in speed. For lists, there is a certain amount of overhead for growing dynamically and general flexibility.

Notice the J function can be used to create a new matrix of a given size. J_{m,n} is the name for the Unit Matrix in linear algebra.

Also notice that a one-dimensional matrix can be indexed with just one subscript. That is, we can use y* instead of y[1]**. That makes it easier to treat matrices as lists, and in the loop above, which is the same in both cases.*

Question until next time: How can the code be made even faster?