MATLAB and its open source alternative Octave are popular mathematical applications. The scipy.io
package has the
savemat
function, which allows you to store NumPy arrays in a .mat
file as a value of a dictionary.
Installing MATLAB or Octave is outside of the scope of this book. The Octave website has some pointers for installing: http://www.gnu.org/software/octave/download.html. Check the See Also section of this recipe, for instructions on installing SciPy, if necessary.
Once you have installed MATLAB or Octave, you need to follow the subsequent steps to store NumPy arrays:
savemat
.Create a NumPy array, and call savemat
to store the array in a .mat
file. This function has two parameters—a file name and a dictionary containing variable names and values.
a = numpy.arange(7) scipy.io.savemat("a.mat", {"array": a})
.mat
file.Navigate to the directory where you created the file. Load the file, and check the array:
octave-3.4.0:2> load a.mat octave-3.4.0:3> array array = 0 1 2 3 4 5 6
The complete code for this recipe is as follows:
import numpy import scipy.io a = numpy.arange(7) scipy.io.savemat("a.mat", {"array": a})