Simple Matlab/Octave tips
How do I extract elements from a matrix, based on a boolean criterion?
I have a
20×2 matrix, i.e. a matrix with 20 lines and two columns. I would like to extract all those lines for which the second element (the one in the second column) is smaller than 0.5.
We will do this one the real Matlab way, in array-based formulation and without loops. It's faster, it's shorter, it's nicer and it's the Matlab way of doing things. First, let us create a
2×20 Matlab matrix, filled with random numbers, to illustrate the procedure:
a = rand(2,20). The next step consists in constructing a matrix that acts as a mask for the boolean condition “second element is smaller than 0.5”. Here you go:
mask = a(:,2)<0.5. We finally extract all lines from
a for which the mask yields
1 (which means,
a_extract = a(mask,:). Alternatively, taking everything on one line, we have
a_extract = a(a(:,2)<0.5,:);
There are fundamentally two strategies for extracting a sub-matrix from some initial matrix. The first is to use a vector containing the sub-indices to extract along every space direction (or the joker
: to keep all indices). The second, to apply a boolean (in Matlab terminology, a
logical) matrix as a mask. The following code snippet illustrates both approaches:
How do I plot data produced by some other program in Matlab?
The result from some of my simulations is a (scalar) velocity field which I'd like to plot with Matlab, as a figure with pixels whos color represents the value of the scalar to be plotted.
For small data sets, you may want to avoid incompatibilities between operating systems and processors by storing the data in a text file. Forget about the dimensions of your matrix and write the data in a single row, one element per line. This strategy then works also for matrices that have more than two dimensions. For example, let's say you want to save a matrix whos content, in Matlab notation, is [0.1, 0.2, 0.3; 1, 2, 3]. To save this one, open a text file
my_matrix.dat and fill it with the following content:
0.1 1.0 0.2 2.0 0.3 3.0
Then, load the matrix into Matlab space, reshape it properly and plot it:
Is there a free version of Matlab?
No, there isn't. There are however some free software packages with similar functionalities. You might want to have a look at Octave, which supports the same syntax as Matlab to a large extent.