Python 到 MATLAB:使用 scipy.io 导出字符串列表

发布于 2024-08-25 06:57:42 字数 505 浏览 4 评论 0 原文

我正在尝试使用 scipy.io 将文本字符串列表从 Python 导出到 MATLAB。我想使用 scipy.io 因为我想要的 .mat 文件应该包含两个数值矩阵(我学会了这样做 此处)和文本元胞数组。

我尝试过:

import scipy.io
my_list = ['abc', 'def', 'ghi']
scipy.io.savemat('test.mat', mdict={'my_list': my_list})

在 MATLAB 中,我加载 test.mat 并获取字符数组:

my_list =

adg
beh
cfi

How do I make scipy.io export a list into a MATLAB cell array?

I am trying to export a list of text strings from Python to MATLAB using scipy.io. I would like to use scipy.io because my desired .mat file should include both numerical matrices (which I learned to do here) and text cell arrays.

I tried:

import scipy.io
my_list = ['abc', 'def', 'ghi']
scipy.io.savemat('test.mat', mdict={'my_list': my_list})

In MATLAB, I load test.mat and get a character array:

my_list =

adg
beh
cfi

How do I make scipy.io export a list into a MATLAB cell array?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

撩发小公举 2024-09-01 06:57:42

您需要使 my_list 成为 numpy 对象的数组:

import scipy.io
import numpy as np
my_list = np.zeros((3,), dtype=np.object)
my_list[:] = ['abc', 'def', 'ghi']
scipy.io.savemat('test.mat', mdict={'my_list': my_list})

然后它将以单元格格式保存。可能有更好的方法将其放入 np.object 中,但我从 Scipy 文档

You need to make my_list an array of numpy objects:

import scipy.io
import numpy as np
my_list = np.zeros((3,), dtype=np.object)
my_list[:] = ['abc', 'def', 'ghi']
scipy.io.savemat('test.mat', mdict={'my_list': my_list})

Then it will be saved in a cell format. There might be a better way of putting it into a np.object, but I took this way from the Scipy documentation.

强者自强 2024-09-01 06:57:42

看起来列表的内容已正确导出,它们只是被转置并放置在字符数组中。您可以通过转置它并使用 CELLSTR,它将每一行放在一个单独的单元格中:

>> my_list = ['adg';'beh';'cfi'];  %# Your example
>> my_list = cellstr(my_list')    %'# A 3-by-1 cell array of strings

my_list = 

    'abc'
    'def'
    'ghi'

当然,这并不能解决将数据作为元胞数组从 Python 导出到 MATLAB 的更一般问题,但它应该有助于解决您上面列出的特定问题。

It looks like the contents of the list are exported properly, they are just transposed and placed in a character array. You can easily convert it to the desired cell array of strings in MATLAB by transposing it and using CELLSTR, which places each row in a separate cell:

>> my_list = ['adg';'beh';'cfi'];  %# Your example
>> my_list = cellstr(my_list')    %'# A 3-by-1 cell array of strings

my_list = 

    'abc'
    'def'
    'ghi'

Granted, this doesn't address the more general issue of exporting data as a cell array from Python to MATLAB, but it should help with the specific problem you list above.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文