You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Python Numpy数组转换为特定格式的Matlab Cell文件

解决Python生成Matlab 1×3 Cell结构的问题

要生成包含1×3 Matlab Cell的文件,每个Cell内是7×5的double矩阵,你需要用numpy object类型数组模拟Matlab的Cell结构——scipy.io.savemat默认会把同形状的数组列表堆叠成多维数组,而非Cell。

修改后的代码

import numpy as np
import scipy.io

# 创建3个7×5的矩阵
mat1 = np.random.randint(1, 100, 35).reshape(7, 5)
mat2 = mat1 * 10
mat3 = mat1 * 0.1

# 创建1×3的object类型数组,对应Matlab的Cell
cell_array = np.empty((1, 3), dtype=object)
cell_array[0, 0] = mat1
cell_array[0, 1] = mat2
cell_array[0, 2] = mat3

# 保存为Matlab文件
scipy.io.savemat("test_py_cell.mat", {'key': cell_array})

验证结果

加载生成的文件后,结构与目标样本完全一致:

sample_mat = scipy.io.loadmat('test_py_cell.mat')
var1 = sample_mat['key']
print(type(var1))  # 输出: <class 'numpy.ndarray'>
print(var1.shape)  # 输出: (1, 3)

var2 = var1[0, 0]
print(type(var2))  # 输出: <class 'numpy.ndarray'>
print(var2.shape)  # 输出: (7, 5)

原理说明

  • Matlab的Cell对应Python中dtype=object的numpy数组,每个元素可存放任意形状的数组
  • 直接传入列表会被scipy.io.savemat自动堆叠成多维数组(3个7×5数组会变成3×7×5),而object数组会被识别为Cell结构
  • 设定数组形状为(1,3),对应Matlab的1×3 Cell矩阵

内容的提问来源于stack exchange,提问作者abhishek

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 20:06:23