Emma
Emma

Reputation: 618

fprintf with mixture of strings and numbers

I would like to produce a text file which includes a mixture of strings and numbers. The example is as follows:

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}];

In order to print R_Values I would simply type:

 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

However, when trying to do this for R_Values1 I fail, Im not sure how to allow for the different format in the first and last line of R_Values1.

Upvotes: 1

Views: 3820

Answers (2)

mlcr
mlcr

Reputation: 335

In MATLAB: to write strings and numbers in the same file, you need to

1) convert number to formatted string using sprintf

2) concat all strings

3) use fprintf to write to file

Example: you want to write Nx1 array Strings and Nx1 array Numbers to 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

Upvotes: 2

Azim J
Azim J

Reputation: 8290

Since the heading row has a different format than the data rows, I see two options.

  1. print the heading row with a separate fprintf statement or;
  2. use xlswrite to write the cell array R_Values1 to a file. According to the MATLAB documentation 'xlswrite' will create a CSV file if Excel is not available otherwise it will create Excel file which might not work for you.

Maybe others might have different suggestions for handling the header row.

Upvotes: 1

Related Questions