MATLAB爱好者论坛-LabFans.com

MATLAB爱好者论坛-LabFans.com (https://www.labfans.com/bbs/index.php)
-   资料存档 (https://www.labfans.com/bbs/forumdisplay.php?f=72)
-   -   如何存储字符串矩阵并写入文件? (https://www.labfans.com/bbs/showthread.php?t=23505)

poster 2019-12-10 20:41

如何存储字符串矩阵并写入文件?
 
我不知道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 那么有什么办法可以做到这一点?



[B]回答:[/B]

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

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

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)

[url=https://stackoverflow.com/questions/2971012]更多&回答...[/url]


所有时间均为北京时间。现在的时间是 10:59

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