We use MATLAB file I/O to read and write MATLAB data files in Python. This helps us share data between MATLAB and Python easily.
MATLAB file I/O (loadmat, savemat) in SciPy
Start learning this pattern below
Jump into concepts and practice - no test required
from scipy.io import loadmat, savemat # Load MATLAB file data = loadmat('filename.mat') # Save data to MATLAB file savemat('filename.mat', {'variable_name': data_to_save})
loadmat loads MATLAB .mat files into a Python dictionary.
savemat saves Python dictionaries to .mat files readable by MATLAB.
mat_data.from scipy.io import loadmat mat_data = loadmat('data.mat')
my_array in the MATLAB file 'output.mat'.from scipy.io import savemat import numpy as np array = np.array([1, 2, 3]) savemat('output.mat', {'my_array': array})
This program saves a dictionary with scores and names to a MATLAB file, then loads it back and prints the contents.
from scipy.io import loadmat, savemat import numpy as np # Create some data to save my_dict = {'scores': np.array([90, 85, 88]), 'names': np.array(['Ann', 'Bob', 'Cara'], dtype=object)} # Save data to MATLAB file savemat('example.mat', my_dict) # Load the data back loaded_data = loadmat('example.mat') # Print loaded data keys and values for key in loaded_data: if not key.startswith('__'): print(f"{key}: {loaded_data[key]}")
MATLAB .mat files store data in a dictionary-like structure when loaded in Python.
Keys starting with '__' in loaded data are metadata and can be ignored.
Use dtype=object for string arrays to avoid issues when saving/loading.
Use loadmat to read MATLAB .mat files into Python dictionaries.
Use savemat to save Python dictionaries as MATLAB .mat files.
This allows easy data exchange between MATLAB and Python.
Practice
What does the scipy.io.loadmat function do?
Solution
Step 1: Understand the function purpose
loadmatis designed to read MATLAB .mat files.Step 2: Identify the output type
It returns the data as a Python dictionary with variable names as keys.Final Answer:
Loads data from a MATLAB .mat file into a Python dictionary -> Option AQuick Check:
loadmat reads .mat files into dict [OK]
- Confusing loadmat with savemat
- Thinking loadmat executes MATLAB code
- Assuming loadmat converts data formats automatically
Which of the following is the correct way to save a Python dictionary data to a MATLAB file named output.mat using savemat?
?
Solution
Step 1: Check savemat function signature
savemat(filename, dict) requires a filename string and a dictionary of variables.Step 2: Wrap data in a dictionary with a variable name
To savedata, it must be inside another dictionary like {'data': data}.Final Answer:
savemat('output.mat', {'data': data}) -> Option DQuick Check:
savemat needs filename and dict [OK]
- Passing data directly without wrapping in dict
- Swapping filename and data arguments
- Using incorrect argument types
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.
Solution
Step 1: Understand loadmat output
loadmat returns a Python dictionary containing MATLAB variables.Step 2: Check the printed type
Printing type of mat_data shows <class 'dict'>.Final Answer:
<class 'dict'> -> Option BQuick Check:
loadmat returns dict [OK]
- Expecting a list or array directly
- Assuming loadmat raises error if file exists
- Confusing output type with variable inside dict
Identify the error in this code snippet:
from scipy.io import savemat
my_data = {'x': [1, 2, 3]}
savemat(my_data, 'data.mat')Solution
Step 1: Check savemat argument order
savemat expects filename first, then dictionary.Step 2: Identify argument swap
Code passes dictionary first, filename second, which is incorrect.Final Answer:
Arguments to savemat are in wrong order -> Option CQuick Check:
savemat(filename, dict) order matters [OK]
- Swapping filename and data arguments
- Assuming lists can't be saved
- Forgetting to import savemat
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?
Solution
Step 1: Understand savemat input format
savemat requires a dictionary mapping variable names to values.Step 2: Check how to save multiple variables
Pass a single dictionary with keys 'a' and 'b' mapped to their values.Step 3: Identify correct option
savemat('vars.mat', {'a': a, 'b': b}) correctly passes {'a': a, 'b': b} as one dictionary.Final Answer:
savemat('vars.mat', {'a': a, 'b': b}) -> Option AQuick Check:
Multiple variables saved in one dict [OK]
- Passing multiple dicts instead of one
- Wrapping variables in extra lists unnecessarily
- Using a single key for multiple variables
