【问题标题】:Cell array in first column, matrix in further columns in text file. How?第一列中的元胞数组,文本文件中其他列中的矩阵。如何?
【发布时间】:2014-12-18 14:53:01
【问题描述】:
A = {'Subject 1'; 'Subject 2'; 'Subject 3'; 'Subject 4'; 'Subject 5'}

有了这个我有他们的相关数据:

ID = [1,2,3,4,5]

Score = [65, 90, 42, 53, 13]

我想以这种格式将数据输出到 .txt 文件中:

Screen Name       ID       Score
Subject 1          1          65
Subject 2          2          90
Subject 3          3          42
Subject 4          4          53
Subject 5          5          13

我知道我需要先转置数据(谢谢 rayryeng)

ID = transpose(ID)
Score = transpose(Score)

所以,我刚刚更新了下面的代码,并带有相关的错误:

fileID = fopen('user_Database.txt', 'w');
fprintf(fileID,'%8s %16s %24s\n', 'Screen Name', 'ID', 'Score');
fprintf(fileID,'%8s %16.2f %24.2f\n', A{:}, ID, Score);

谢谢 Robert P.:它不再崩溃,但是它没有输入第二个 fprintf 行的数据。第一个 fprintf 行很好......

我将如何写出 fprintf 以将单元格数组合并到第一列中,并将矩阵合并到后续列中?

【问题讨论】:

  • 它不再给出错误,但它没有打印出数据。它只打印出上面发布的第一条 fprintf() 行。

标签: arrays matlab file text matrix


【解决方案1】:

看看这是否适合你 -

%// Inputs (slightly modified from original ones to show spacings are taken care of)
A = {'Subject 1'; 'Subject 2'; 'Subject 3'; 'Subject 4'; 'Subject 5'}
ID = [101,2,3,201,8]
Score = [165, 2090, 42, 53, 13]

%// Create cell array versions of ID and Score to account for proper
%// spacings between the prints of ID and Score
Score_cell = cellstr(num2str(Score.')); %//'
ID_cell = cellstr(num2str(ID.')); %//'

output_file = 'results.txt'; %//'# Edit if needed to be saved to a different path
fid = fopen(output_file, 'w+'); %// open file for writing

fprintf(fid, 'Screen Name\t  ID\tScore\n'); %// write the header line
for ii=1:numel(A)
    fprintf(fid, '%s\t %s\t %s\n',A{ii}, ID_cell{ii},Score_cell{ii}); %// write data
end
fclose(fid); %// close file as writing is done

代码运行-

>> type results.txt

Screen Name   ID    Score
Subject 1    101      165
Subject 2      2     2090
Subject 3      3       42
Subject 4    201       53
Subject 5      8       13

【讨论】:

  • 没关系,如果有问题我可以回到这里。我正在尝试使用更多列来测试代码。谢谢。
猜你喜欢
  • 1970-01-01
  • 2019-09-19
  • 2011-12-20
  • 1970-01-01
  • 1970-01-01
  • 2018-06-22
  • 1970-01-01
  • 2021-04-22
  • 2020-09-20
相关资源
最近更新 更多