【发布时间】: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
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
这里只给几个镜头,以适合你的为准!
%// 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
如果您想要一个与元胞数组版本完全相似的输出,您可以使用基于 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]}
如果你对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]}
【讨论】:
S',即S的转置。
brackets and commas?你能告诉我们文本文件在文本编辑器中打开时的样子吗?
【讨论】:
clear all,在您的示例中定义M,然后按原样粘贴我的代码
S。那里没有空格。问题似乎是dlmwrite。使用dlmwrite('tmp.txt',S,'')。我已经用最后一部分编辑了我的答案