Python中提取.mat文件Cell对象数组内的Numpy数组求助
Hey there, let’s work through this together! I’ve dealt with this exact quirk of scipy.io.loadmat translating MATLAB cell arrays into Python before—those (1, N) object arrays can feel a bit clunky at first, but it’s easy to extract your data once you know the trick.
Here’s how to get those (128,128) arrays out cleanly:
Step 1: Load the data safely (skip the locals().update() trick)
First, avoid using locals().update(data)—it can accidentally overwrite existing variables in your namespace. Instead, directly pull the bspec array from the loaded dictionary:
from scipy.io import loadmat import numpy as np # Load the .mat file into a dictionary data = loadmat('bispec.mat') # Extract the bspec object array directly bspec = data['bspec']
Step 2: Flatten the (1, 260) array to 1D
The bspec array is shaped (1, 260), meaning it’s a single row of 260 elements. We can strip that extra singleton dimension to make iteration easier:
# Convert (1, 260) to (260,) using squeeze() bspec_flat = bspec.squeeze() # Alternatively, use explicit indexing: bspec_flat = bspec[0]
Step 3: Extract your (128,128) arrays
Now you have a 1D array of 260 elements, each being a (128,128) numpy array. You have two common options here:
Option 1: Extract into a list of individual arrays
If you want to work with each (128,128) array separately (e.g., processing one at a time), use a list comprehension:
bspec_arrays = [arr for arr in bspec_flat] # Now bspec_arrays[0] is your first (128,128) array, bspec_arrays[1] the second, etc.
Option 2: Stack into a single 3D numpy array
If you need to perform batch operations (like matrix math across all arrays), stack them into a single 3D array:
bspec_3d = np.stack(bspec_flat, axis=0) # The shape here will be (260, 128, 128)
Quick note on what’s happening
MATLAB cell arrays are 1-indexed and often stored as 2D even when they’re logically 1D. scipy.io.loadmat preserves that structure, hence the (1,260) shape. Using squeeze() or bspec[0] just removes that unnecessary first dimension to make the array behave like a normal 1D collection in Python.
内容的提问来源于stack exchange,提问作者user3806397

