Save and load NumPy arrays with MATLAB .mat files using SciPy
NumPy: I/O Operations Exercise-17 with Solution
Write a NumPy program that saves a NumPy array to a MATLAB .mat file using scipy.io.savemat and then reads it back using scipy.io.loadmat.
Sample Solution:
Python Code:
import numpy as np
import scipy.io
# Create a NumPy array
array_to_save = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
# Define the file name to save the .mat file
mat_file_name = 'array_data.mat'
# Save the NumPy array to a .mat file
scipy.io.savemat(mat_file_name, {'array': array_to_save})
# Load the data back from the .mat file
loaded_data = scipy.io.loadmat(mat_file_name)
# Retrieve the array from the loaded data
loaded_array = loaded_data['array']
# Print the loaded array to verify it matches the original array
print('Loaded array:\n', loaded_array)
Output:
Loaded array: [[1 2 3] [4 5 6] [7 8 9]]
Explanation:
- Import Libraries:
- Imported numpy as np for array creation.
- Imported scipy.io for saving and loading .mat files.
- Create a NumPy Array:
- Created a 3x3 NumPy array named array_to_save.|
- Define File Name:
- Set the .mat file name to array_data.mat.
- Save Array to .mat File:
- Used scipy.io.savemat to save array_to_save to the specified .mat file, under the variable name 'array'.
- Load Data from .mat File:
- Used scipy.io.loadmat to read the data from the .mat file into a dictionary named loaded_data.
- Retrieve Array from Loaded Data:
- Extracted the array from loaded_data using the key 'array'.
- Print the Loaded Array:
- Printed the loaded array to verify it matches the original array.
Python-Numpy Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: How to write a NumPy array to a SQLite database and read it back?
Next: Read PNG image data into NumPy array using Python.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/python-exercises/numpy/save-and-load-numpy-arrays-with-matlab-dot-mat-files-using-scipy.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics