Labfans是一个针对大学生、工程师和科研工作者的技术社区。 论坛首页 | 联系我们(Contact Us)
MATLAB爱好者论坛-LabFans.com
返回   MATLAB爱好者论坛-LabFans.com > 其它 > 资料存档
资料存档 资料存档
回复
 
主题工具 显示模式
旧 2019-12-10, 20:41   #1
poster
高级会员
 
注册日期: 2019-11-21
帖子: 3,006
声望力: 66
poster 正向着好的方向发展
帖子 如何存储字符串矩阵并写入文件?

我不知道Matlab是否可以做到这一点,但我想将一些字符串存储在4×3的矩阵中,矩阵中的每个元素都是一个字符串。

test_string_01 test_string_02 test_string_03 test_string_04 test_string_05 test_string_06 test_string_07 test_string_08 test_string_09 test_string_10 test_string_11 test_string_12 然后,我想将此矩阵写入纯文本文件,以逗号或空格分隔。

test_string_01,test_string_02,test_string_03 test_string_04,test_string_05,test_string_06 test_string_07,test_string_08,test_string_09 test_string_10,test_string_11,test_string_12 似乎matrix数据类型无法存储字符串。我看着cell 。我尝试使用dlmwrite()或csvwrite() ,但是它们都只接受矩阵。我也首先尝试了cell2mat() ,但是那样字符串中的所有字母都用逗号分隔,例如

t,e,s,t,_,s,t,r,i,n,g,_,0,1,t,e,s,t,_,s,t,r,i,n,g,_,0,2,t,e,s,t,_,s,t,r,i,n,g,_,0,3 那么有什么办法可以做到这一点?



回答:

单元格数组是存储字符串的方法。

我同意将字符串保存到文本文件是很痛苦的,但是您可以使用以下代码来实现:

strings = { 'test_string_01','test_string_02','test_string_03' 'test_string_04','test_string_05','test_string_06' 'test_string_07','test_string_08','test_string_09' 'test_string_10','test_string_11','test_string_12'}; fid = fopen('output.txt','w'); for row = 1:size(strings,1) fprintf(fid, repmat('%s\t',1,size(strings,2)-1), strings{row,1:end-1}); fprintf(fid, '%s\n', strings{row,end}); end fclose(fid); 用\t代替,以获取csv文件。

您还可以使用XLSWRITE将字符串的单元格数组存储到Excel文件中(需要COM接口,因此仅在Windows上):

xlswrite('output.xls',strings)

更多&回答...
poster 当前离线   回复时引用此帖
回复


发帖规则
不可以发表新主题
不可以发表回复
不可以上传附件
不可以编辑自己的帖子

启用 BB 代码
论坛禁用 表情符号
论坛启用 [IMG] 代码
论坛启用 HTML 代码



所有时间均为北京时间。现在的时间是 22:58


Powered by vBulletin
版权所有 ©2000 - 2025,Jelsoft Enterprises Ltd.