【问题标题】:Matlab:How from the matrix M, I can have the format S in a text file?Matlab:如何从矩阵 M 中获得文本文件中的格式 S?
【发布时间】:2015-02-21 17:42:25
【问题描述】:
M=[2    5    6
   4    8    9
   11  55    4
   89   2   47]

S = {[2    5    6],[4    8    9],[11   55    4],[89    2    47]}

如何从矩阵 M 中获得文本文件中的格式 S?

【问题讨论】:

    标签: matlab matrix text-files


    【解决方案1】:

    这里只给几个镜头,以适合你的为准!

    第 1 枪

    %// Form the cell array version of the input matrix, M
    S = mat2cell(M,ones(1,size(M,1)),size(M,2))
    
    %// Write to text file 
    output_file = 'results.txt'
    dlmwrite(output_file,S,' ');
    

    代码运行-

    >> type results.txt
    
    2 5 6
    4 8 9
    11 55 4
    89 2 47
    

    第 2 枪

    如果您想要一个与元胞数组版本完全相似的输出,您可以使用基于 fprintf 的解决方案 -

    %// S used in this code would come from the earlier codes
    output_file = 'results.txt'
    
    fid = fopen(output_file, 'w+');
    fprintf(fid, '{')                          %// Write the starting curly bracket
    for ii=1:numel(S)-1
        fprintf(fid, '[%s],',num2str(S{ii}));  %// Write all data except the final cell
    end
    fprintf(fid, '[%s]',num2str(S{end}));  %// Write the data for final cell, 
                                            %// as it does not need any comma after it
    fprintf(fid, '}')                       %// Write the ending curly bracket
    fclose(fid);
    

    代码运行-

    >> type results.txt
    
    {[2  5  6],[4  8  9],[11  55   4],[89   2  47]}
    

    第 3 枪

    如果你对square brackets内部的数字之间的不规则间距不太满意,可以直接使用M,将使用fprintf的两行处的S替换为数据-

    在循环内部 -

    fprintf(fid, '[%d %d %d]',M(ii,1),M(ii,2),M(ii,3));
    

    循环退出后-

    fprintf(fid, '[%d %d %d]',M(end,1),M(end,2),M(end,3));
    

    代码运行-

    >> type results.txt
    
    {[2 5 6][4 8 9][11 55 4][89 2 47]}
    

    【讨论】:

    • @Divakar:我想要的结果完全是这种形式:{[2 5 6],[4 8 9],[11 55 4],[89 2 47]}
    • @bzak 使用S',即S的转置。
    • @Divakar:带括号和逗号!
    • @bzak 你是说文本文件中的brackets and commas?你能告诉我们文本文件在文本编辑器中打开时的样子吗?
    • @Divakar: {[2 5 6],[4 8 9],[11 55 4],[89 2 47]}
    【解决方案2】:

    使用mat2str 进行基本工作和regexprepstrrep 进行微调(感谢@Divakar 提醒我后一个功能):

    S = regexprep(['{' mat2str(M) '}' ], ';', '],[');
    

    S = strrep(['{' mat2str(M) '}' ], ';', '],[');
    

    然后,要写入文件,请使用

    dlmwrite('tmp.txt', S, '')
    

    【讨论】:

    • @Divakar 我不记得那个函数了。谢谢!我已经添加了
    • @LuisMendo:您的答案为 89 (8 9) 提供了 8 到 9 之间的空间,对于 11 (1 1)、55 (5 5) 和 47 (4 7) 也是如此!
    • @bzak ??不,它没有。执行clear all,在您的示例中定义M,然后按原样粘贴我的代码
    • @LuisMendo: clc;清除所有; M=[2 5 6 4 8 9 11 55 4 89 2 47]; S = strrep(['{' mat2str(M) '}' ], ';', '],['); %// 写入文本文件 output_file = 'results.txt'; dlmwrite(output_file,S,' ');
    • @bzak 观看 S。那里没有空格。问题似乎是dlmwrite。使用dlmwrite('tmp.txt',S,'')。我已经用最后一部分编辑了我的答案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多