Save and load NumPy arrays with MATLAB .mat files using SciPy
17. MATLAB .mat File Round-trip
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:
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.
For more Practice: Solve these Related Problems:
- Write a Numpy program to save an array to a MATLAB .mat file using scipy.io.savemat and then load it back, verifying all keys and shapes.
- Write a Numpy program to export a structured array to a .mat file and then convert specific fields to a different type upon reloading.
- Write a Numpy program to save multiple arrays into a .mat file and then extract one array for further MATLAB-compatible processing.
- Write a Numpy program to write an array to a .mat file, modify the file externally, and then load it back into Python to check for consistency.
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.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics