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!