Python 到 Mat 文件 : export list of string to ordinar matrix of chars (not a cell-array! )

标签 python matlab scipy mat-file

Python 上的此代码在 .mat 文件中创建单元格“STRINGS”:

data = {"STRINGS": numpy.empty((0),dtype=numpy.object)}
data["STRINGS"] = numpy.append( data["STRINGS"], "Some string" )
scipy.io.savemat( output_mat_file, data )

在 matlab 中我得到单元格字符串:

>> STRINGS{1}

ans =

Some string

如何获得普通矩阵?例如:

>> strings(1,:) = char('Some ');
>> strings(1,:)

ans =

Some 

编辑

如果我运行以下代码,我会被误解数组修饰。

Python:

list = ['hello', 'world!!!']
scipy.io.savemat(output_mat_file, mdict={'list':list})

Matlab:

>> list
list =
hlo wrd!

最佳答案

在 MATLAB 中,元胞数组是异构数据类型的容器,而矩阵则不是,并且它们的所有元素必须属于同一类型(无论是数字 double 还是字符)

矩阵是矩形的(因此,如果您在每个二维矩阵行中存储字符串,它们都必须具有相同的长度,或者用空格填充)。这个概念也适用于多维矩阵。

Python 列表的 MATLAB 等效项是元胞数组:

Python

x = [1, 10.0, 'str']
x[0]

马尔塔布

x = {int32(1), 10, 'str'}
x{1}

编辑:

下面是一个显示差异的示例:

Python

import numpy
import scipy.io

list = ['hello', 'world!!!']
scipy.io.savemat('file.mat', mdict={'list':list})

list2 = numpy.array(list, dtype=numpy.object)
scipy.io.savemat('file2.mat', mdict={'list2':list2})

MATLAB

>> load file.mat
>> load file2.mat
>> whos list list2
  Name       Size            Bytes  Class    Attributes

  list       2x8                32  char               
  list2      2x1               146  cell   

现在我们可以访问字符串:

>> list(1,:)
ans =
hello   

>> list2{1}
ans =
hello

请注意,在矩阵情况下,字符串用空格填充,以便所有字符串具有相同的长度(您可以使用 STRTRIM)

关于Python 到 Mat 文件 : export list of string to ordinar matrix of chars (not a cell-array! ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7464632/

相关文章:

matlab - 如果我们为它赋值(MATLAB),如何取回清除命令?

image - 使用 Matlab 进行男性/女性分类 - 关于寻找平均图像

python - 如何使用 solve_ivp 通过精确点?

python - 将函数与 Python(sympy、quad)集成,其中结果是我想要绘制的另一个函数

Python boto3 SNS 电子邮件格式(每个字符串换行)

python - 网页抓取工具不会转到正确的页面

matlab - 为什么此表达式的计算结果为 0?

python - scipy 优化 fmin 语法

python - 数学算法失败但似乎正确

python - 使用 Ansible 连接到 AWS EC2 实例