nicer outcome from fprintf
2 ビュー (過去 30 日間)
古いコメントを表示
I'm looking for a better way of saving data into a text file. I'm currently using fprintf, but when the data is saved as a text file I cant seem to get the data to be displayed as was expected. I would like the data to appear as if it was in a table (without the grids obviously). Example:
clear all
AirT = {rand(32,1),rand(32,1),rand(32,1),rand(32,1)};
SolRad = {rand(32,1),rand(32,1),rand(32,1),rand(32,1)};
Rain = {rand(32,1),rand(32,1),rand(32,1),rand(32,1)};
Location = {'England','Wales','Scotland','Ireland'};
CorrVariables = {'AirT','SolRad','Rain'};
for i = 1:length(Location);
Data = @(location) struct('Location',location,CorrVariables{1},AirT{i},...
CorrVariables{2},SolRad{i},CorrVariables{3},Rain{i});
D(i) = Data(Location{i});
end
FieldName = {D.Location};
R = corrcoef([D.AirT],'rows','pairwise');
R_Value = [Location(nchoosek(1:size(R,1),2)) num2cell(nonzeros(tril(R,-1)))];
mkdir(fullfile('C:\Correlation'));
CorrFile = 'C:\Correlation';
for i= 1:length(CorrVariables);
filename{i} = fullfile(CorrFile,[CorrVariables{i} '.txt']);
fid{i} = fopen(filename{i},'wt');
for j = 1:length(R_Value)
fprintf(fid{i},'%s\t%s\t%f\n',R_Value{j,1},R_Value{j,2},R_Value{j,3});
end
end
Which generates a text file of a similar format to name, name, R_Value thus showing which variables were used to calculate the correlation value.
However, as the names of the variables are of different sizes, the text files generated do not look as good as I would have hoped i.e. the names and the correlation values do not lie on top of one another as you would get in a table. Is there any way of producing a nicer outcome for what I'm trying to do?
0 件のコメント
採用された回答
Andrew Newell
2012 年 2 月 28 日
There are two approaches you could use. One is just to specify the width of each field:
fprintf(fid{i},'%12s\t%12s\t%9.6f\n', ...)
Another is to convert your cell arrays into arrays of strings so each country name is padded with blanks until they are the same length:
country1 = char(R_Value{:,1});
country2 = char(R_Value{:,2});
....
fprintf(fid,'%s\t%s\t%9.6f\n',country1(j,:),country2(j,:),R_Value{j,3});
Either way, you need to provide extra formatting info for the numbers to get them lined up.
0 件のコメント
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Cell Arrays についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!