Bird
Raised Fist0
SciPydata~10 mins

MATLAB file I/O (loadmat, savemat) in SciPy - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - MATLAB file I/O (loadmat, savemat)
Start: Prepare data in Python
Use savemat() to save data to .mat file
File saved on disk
Use loadmat() to read .mat file
Data loaded back into Python
Use data for analysis or display
End
This flow shows saving Python data to a MATLAB .mat file and then loading it back into Python using scipy functions.
Execution Sample
SciPy
from scipy.io import savemat, loadmat

# Save data
data = {'x': [1, 2, 3], 'y': [4, 5, 6]}
savemat('datafile.mat', data)

# Load data
loaded = loadmat('datafile.mat')
print(loaded)
This code saves a dictionary to a .mat file and then loads it back, printing the loaded data.
Execution Table
StepActionInput/VariableResult/Output
1Prepare data dictionarydata = {'x': [1,2,3], 'y': [4,5,6]}{'x': [1,2,3], 'y': [4,5,6]}
2Call savemat()savemat('datafile.mat', data)File 'datafile.mat' created with variables x and y
3Call loadmat()loadmat('datafile.mat')Dictionary with keys: '__header__', '__version__', '__globals__', 'x', 'y'
4Print loaded dataprint(loaded){'__header__': ..., '__version__': ..., '__globals__': ..., 'x': array([[1], [2], [3]]), 'y': array([[4], [5], [6]])}
5EndN/AData loaded successfully from .mat file
💡 Data saved and loaded successfully; loadmat adds metadata keys automatically
Variable Tracker
VariableStartAfter savematAfter loadmatFinal
data{'x': [1,2,3], 'y': [4,5,6]}No changeNo changeNo change
loadedN/AN/A{'__header__': ..., 'x': array([[1], [2], [3]]), 'y': array([[4], [5], [6]])}Same as after loadmat
Key Moments - 2 Insights
Why does loadmat output include keys like '__header__' and '__version__'?
loadmat always adds metadata keys to the loaded dictionary to store file info. Your saved variables appear as keys alongside these.
Why are the loaded arrays wrapped in 2D arrays like array([[1], [2], [3]])?
MATLAB stores arrays as 2D by default, so loadmat returns them as 2D numpy arrays even if originally 1D lists.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what does savemat() do at step 2?
ALoads data from a .mat file
BPrints the data dictionary
CCreates a .mat file with the given variables
DDeletes the .mat file
💡 Hint
See step 2 in execution_table where savemat creates the file
At which step does loadmat() add metadata keys like '__header__'?
AStep 3
BStep 2
CStep 1
DStep 4
💡 Hint
Check step 3 in execution_table where loadmat returns dictionary with metadata keys
If the original data had a variable 'z', what would happen in the loaded dictionary?
AThe loaded dictionary would exclude 'z'
BThe loaded dictionary would include key 'z' with its data
CThe file would fail to save
DThe loaded dictionary would only have metadata keys
💡 Hint
savemat saves all keys; loadmat loads all saved variables as keys
Concept Snapshot
Use savemat(filename, dict) to save Python dict data to a MATLAB .mat file.
Use loadmat(filename) to load .mat file data back into Python as a dict.
loadmat adds metadata keys like '__header__' automatically.
Arrays load as numpy arrays, often 2D by default.
This allows easy data exchange between Python and MATLAB.
Full Transcript
This visual execution trace shows how to save Python data to a MATLAB .mat file using scipy's savemat function, and then load it back using loadmat. First, a Python dictionary with lists is prepared. Then savemat writes this data to a file named 'datafile.mat'. Next, loadmat reads this file and returns a dictionary that includes the saved variables plus some metadata keys like '__header__'. The loaded arrays appear as 2D numpy arrays. This process allows sharing data between Python and MATLAB easily.

Practice

(1/5)
1.

What does the scipy.io.loadmat function do?

easy
A. Loads data from a MATLAB .mat file into a Python dictionary
B. Saves a Python dictionary as a MATLAB .mat file
C. Converts Python lists to MATLAB arrays
D. Executes MATLAB code from Python

Solution

  1. Step 1: Understand the function purpose

    loadmat is designed to read MATLAB .mat files.
  2. Step 2: Identify the output type

    It returns the data as a Python dictionary with variable names as keys.
  3. Final Answer:

    Loads data from a MATLAB .mat file into a Python dictionary -> Option A
  4. Quick Check:

    loadmat reads .mat files into dict [OK]
Hint: Remember: loadmat reads, savemat writes [OK]
Common Mistakes:
  • Confusing loadmat with savemat
  • Thinking loadmat executes MATLAB code
  • Assuming loadmat converts data formats automatically
2.

Which of the following is the correct way to save a Python dictionary data to a MATLAB file named output.mat using savemat?

?
easy
A. savemat('output.mat', data)
B. savemat(data, 'output.mat')
C. savemat({'output.mat': data})
D. savemat('output.mat', {'data': data})

Solution

  1. Step 1: Check savemat function signature

    savemat(filename, dict) requires a filename string and a dictionary of variables.
  2. Step 2: Wrap data in a dictionary with a variable name

    To save data, it must be inside another dictionary like {'data': data}.
  3. Final Answer:

    savemat('output.mat', {'data': data}) -> Option D
  4. Quick Check:

    savemat needs filename and dict [OK]
Hint: savemat needs dict with variable names as keys [OK]
Common Mistakes:
  • Passing data directly without wrapping in dict
  • Swapping filename and data arguments
  • Using incorrect argument types
3.

What will be the output of the following code?

from scipy.io import loadmat
mat_data = loadmat('sample.mat')
print(type(mat_data))

Assume sample.mat is a valid MATLAB file.

medium
A. <class 'numpy.ndarray'>
B. <class 'dict'>
C. <class 'list'>
D. FileNotFoundError

Solution

  1. Step 1: Understand loadmat output

    loadmat returns a Python dictionary containing MATLAB variables.
  2. Step 2: Check the printed type

    Printing type of mat_data shows <class 'dict'>.
  3. Final Answer:

    <class 'dict'> -> Option B
  4. Quick Check:

    loadmat returns dict [OK]
Hint: loadmat output is always a dict [OK]
Common Mistakes:
  • Expecting a list or array directly
  • Assuming loadmat raises error if file exists
  • Confusing output type with variable inside dict
4.

Identify the error in this code snippet:

from scipy.io import savemat
my_data = {'x': [1, 2, 3]}
savemat(my_data, 'data.mat')
medium
A. Dictionary keys must be strings
B. List values cannot be saved in .mat files
C. Arguments to savemat are in wrong order
D. Missing import statement

Solution

  1. Step 1: Check savemat argument order

    savemat expects filename first, then dictionary.
  2. Step 2: Identify argument swap

    Code passes dictionary first, filename second, which is incorrect.
  3. Final Answer:

    Arguments to savemat are in wrong order -> Option C
  4. Quick Check:

    savemat(filename, dict) order matters [OK]
Hint: Filename is first argument in savemat [OK]
Common Mistakes:
  • Swapping filename and data arguments
  • Assuming lists can't be saved
  • Forgetting to import savemat
5.

You want to save two variables, a = [1, 2, 3] and b = [[4, 5], [6, 7]], into a MATLAB file vars.mat. Which code correctly saves both variables so MATLAB can load them as a and b?

hard
A. savemat('vars.mat', {'a': a, 'b': b})
B. savemat('vars.mat', {'vars': [a, b]})
C. savemat('vars.mat', {'a': [a], 'b': [b]})
D. savemat('vars.mat', {'a': a}, {'b': b})

Solution

  1. Step 1: Understand savemat input format

    savemat requires a dictionary mapping variable names to values.
  2. Step 2: Check how to save multiple variables

    Pass a single dictionary with keys 'a' and 'b' mapped to their values.
  3. Step 3: Identify correct option

    savemat('vars.mat', {'a': a, 'b': b}) correctly passes {'a': a, 'b': b} as one dictionary.
  4. Final Answer:

    savemat('vars.mat', {'a': a, 'b': b}) -> Option A
  5. Quick Check:

    Multiple variables saved in one dict [OK]
Hint: Use one dict with all variables as keys [OK]
Common Mistakes:
  • Passing multiple dicts instead of one
  • Wrapping variables in extra lists unnecessarily
  • Using a single key for multiple variables