I promised to write a short series about programming in M, to try and show some of it's cool features. For those who don't know, M is the scripting language used by Matlab (proprietary) and Octave (Free). M is designed for linear algebra and engineering simulations.
Statements in M are very similar to statements like we would see in languages like C and JavaScript. Statements take very similar syntax, and are (mostly) terminated with a semicolon:
x = 1;
x = sin(y) + 1;
When I said "mostly" above referring to the semicolons because they ar optional. If you leave the semicolon off the end, the value of the statement is printed to the terminal:
Write this: x = (3 + 5) * 2
And get this: x = 16
If you don't assign the value to a variable, you get the result stored in the default variable "ans"
Write this: 3 + (5 * 2)
Get this: ans = 13
M is based on matrices, so dealing with them is very easy:
x = [1 2 3; 4 5 6]
In the matrix constructor, the semicolons separate rows in the matrix. Elements in the row can be separated by commas or whitespace.
Matrices are used for working with strings too. Strings in a row are concatenated together:
x = ["hello ", "world"]
prints:
x = hello world
A matrix can either be treated like a string or like a regular numerical matrix, so writing this:
x = ["ok ", 49]
prints this:
x = ok 1
We've actually used something very similar to that in the Matrixy test suite.
Combining matrices together is also very easy:
x = [1, 2, 3];
y = [4, 5, 6];
z = [x y]
prints this:
z = 1 2 3 4 5 6
As rows:
z = [x;y]
prints this:
z =
1 2 3
4 5 6
One caveat about matrices is that they must be uniform rectangular matrices. You can't have rows that are different lengths:
x = [1 2 3]
y = [4 5 6 7]
z = [x;y] % error!
This caveat is actually relaxed when it comes to strings, you can have strings of different lengths on different rows.
So that's a quick introduction to statements in M. Throughout the week I'll post more information about other aspects of it.