YouTip LogoYouTip

Scipy Matlab Arrays

# SciPy Matlab Arrays NumPy provides methods for saving data in a Python-readable format. SciPy provides methods for interacting with Matlab. SciPy's `scipy.io` module provides many functions for handling Matlab arrays. ### Exporting Data in Matlab Format The **`savemat()`** method can export data in Matlab format. The parameters for this method are: * **filename** - The filename to save the data. * **mdict** - A dictionary containing the data. * **do_compression** - A boolean value specifying whether the resulting data should be compressed. The default is False. Export an array as a variable named "vec" to a mat file: ## Example ```python from scipy import io import numpy as np arr = np.arange(10) io.savemat('arr.mat',{"vec": arr}) **Note:** The code above will save a file named "arr.mat" on your computer. ### Importing Matlab Format Data The `loadmat()` method can import Matlab format data. The parameters for this method are: * **filename** - The filename where the data is saved. It returns a structured array where the keys are variable names and the corresponding values are the variable values. The following example imports an array from a mat file: ## Example ```python from scipy import io import numpy as np arr = np.array([0,1,2,3,4,5,6,7,8,9,]) # Export io.savemat('arr.mat',{"vec": arr}) # Import mydata = io.loadmat('arr.mat') print(mydata) The returned result is as follows: ```python { '__header__': b'MATLAB 5.0 MAT-file Platform: nt, Created on: Tue Sep 22 13:12:32 2020', '__version__': '1.0', '__globals__': [], 'vec': array([[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]]) } Using the variable name "vec" to display only the array from the matlab data: ## Example ```python from scipy import io import numpy as np arr = np.array([0,1,2,3,4,5,6,7,8,9,]) # Export io.savemat('arr.mat',{"vec": arr}) # Import mydata = io.loadmat('arr.mat') print(mydata['vec']) The returned result is as follows: ```python [] From the result, we can see that the array was originally one-dimensional, but it gained an extra dimension during extraction, becoming a two-dimensional array. To solve this problem, you can pass an additional parameter `squeeze_me=True`: ## Example ```python from scipy import io import numpy as np arr = np.array([0,1,2,3,4,5,6,7,8,9,]) # Export io.savemat('arr.mat',{"vec": arr}) # Import mydata = io.loadmat('arr.mat', squeeze_me=True) print(mydata['vec']) The returned result is as follows: ```python [](#)(#) (#)[](#) [Volcengine Coding Plan supports mainstream large models like Doubao, GLM, DeepSeek, Kimi, MiniMax, officially supplied and reliable. Configuration Guide Β₯9.9/month Subscribe Now](https://maas.xfyun.cn/modelSquare?ch=maas_lm_l2E)
← Scipy Significance TestsJava String Regionmatches β†’