2012-03-01 123 views
1

我想生成一个文本文件,其中包含字符串和数字的混合。该示例如下:fprintf与字符串和数字的混合

clear all 
fakeData = @(location) struct('Location',location,'AirT',rand(320,1),'SolRad',rand(320,1),'Rain',rand(320,1)); 
    s(1) = fakeData('England'); 
    s(2) = fakeData('Wales'); 
    s(3) = fakeData('Scotland'); 
    s(4) = fakeData('Ireland'); 
FieldName = {s.Location}; 
R = corrcoef([s.AirT],'rows','pairwise'); 
R_Values = [FieldName(nchoosek(1:size(R,1),2)) num2cell(nonzeros(tril(R,-1)))]; 
MeanCorr = mean(cell2mat(R_Values(:,3))); 
Headings = {'L1','L2','Correlation'}; 
R_Values1 = [Headings;R_Values]; 
R_Values1 = [R_Values1; {'','Mean',MeanCorr}]; 

为了打印R_Values我想简单地键入:

for i=11:length(R_Values); 
fprintf(1,'%12s\t%12s\t%9.6f\n',R_Values{i,1},R_Values{i,2},R_Values{i,3}) 
    end 

然而,试图为R_Values1做到这一点时,我失败了,林不知道如何允许R_Values1的第一行和最后一行的格式不同。

回答

1

由于标题行的格式与数据行不同,因此我会看到两个选项。

  1. 用单独的fprintf声明打印标题行;
  2. 使用xlswrite将单元阵列R_Values1写入文件。根据MATLAB documentation'xlswrite'将创建一个CSV文件,如果Excel不可用,否则它将创建可能不适合您的Excel文件。

也许别人可能对处理标题行有不同的建议。

+0

经过一些试验和错误后,我发现用fprintf替换为: fprintf(1,'% - 12s \ t%-12s \ t%-12s \ n',R_Values1 {i,1},R_Values1 {i,2},R_Values1 {i,3}) 代码确实写入的格式正确,但与R_Values1中的代码不完全相同 – Emma 2012-03-01 20:26:57

+0

只用单独的fprintf语句尝试打印标题行,并且工作完美。谢谢。 – Emma 2012-03-01 20:32:41

+0

@ user1155751很高兴有帮助。 – Azim 2012-03-01 21:45:04

2

在MATLAB:写在同一个文件中的字符串和数字,你需要

1)使用的sprintf

2)CONCAT所有字符串

3)使用fprintf中转换号码格式的字符串写入文件

例子:你想写NX1数组和字符串数组NX1数字到Fileout.txt

% define output file and clean old versions: 
    fileout='Fileout.txt' 
    system(['rm -f ' fileout]); 

    % open output file in the 'a'ppend mode 
    fid=fopen(fileout,'a'); 

    % loop over all lines of both arrays: 
    for i= 1:size(Numbers,1) 
     s = sprintf('%10.3f',Numbers(i)); 
     fprintf(fid,'%s\n',[Strings(i,:) s]); 
    end 
+0

有没有可能没有循环? – Lupocci 2017-11-08 18:30:28

相关问题