【问题标题】:How to store string matrix and write to a file?如何存储字符串矩阵并写入文件?
【发布时间】:2011-02-27 14:22:49
【问题描述】:

我不知道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

那么有什么办法可以做到吗?

【问题讨论】:

  • 在 Matlab 中处理文本是一种痛苦。这在 Python 中可能需要 5 行代码。为什么需要这样做?
  • @Hamish Grubijan 因为我有其他人的现有代码输出矩阵。我想用实际名称替换第一列。
  • @Hamish Grubijan:幸运的是,在 Matlab 中也只需要 5 行代码。

标签: string matlab matrix cell


【解决方案1】:

在大多数情况下,您可以使用分隔符 ' ' 并让 Matlab 使用 dlmwrite 将字符串保存到文件中。

例如,

output=('my_first_String'); dlmwrite('myfile.txt',output,'delimiter','')

将保存一个名为 myfile.txt 的文件,其中包含 my_first_String。

【讨论】:

    【解决方案2】:

    可以稍微缩短yuk的解决方案。

    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');
    fmtString = [repmat('%s\t',1,size(strings,2)-1),'%s\n'];
    fprintf(fid,fmtString,strings{:});
    fclose(fid);
    

    【讨论】:

      【解决方案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)
      

      【讨论】:

      • 我的解决方案太长,无法发表评论。如果您更新您的解决方案,我将删除我的答案。
      • @Jonas,感谢您提供更好的代码。它绝对应该是一个单独的答案。 (至于我,我会接受你的。)对我来说太糟糕了,昨天已经很晚了。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-29
      • 2015-05-31
      • 1970-01-01
      • 2021-10-16
      • 2014-11-28
      相关资源
      最近更新 更多