Time for action – saving and loading a .mat file

If we start with NumPy arrays and decide to use said arrays within a MATLAB or Octave environment, the easiest thing to do is create a .mat file. We can, then, load the file within MATLAB or Octave. Let's go through the necessary steps:

  1. Create a NumPy array and call the savemat() function to create a .mat file. This function has two parameters: a file name and a dictionary containing variable names and values:
    a = np.arange(7)
    
    io.savemat("a.mat", {"array": a})
  2. Within a MATLAB or Octave environment, load the .mat file and check the stored array:
    octave-3.4.0:7> load a.mat
    octave-3.4.0:8> a
    
    octave-3.4.0:8> array
    array =
    
      0
      1
      2
      3
      4
      5
      6

What just happened?

We created a .mat file from NumPy code and loaded ...

Get NumPy : Beginner's Guide - Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.