fprintf for 6 array in double type and 2 date vectors

5 ビュー (過去 30 日間)
Omer Yasin Birey
Omer Yasin Birey 2019 年 1 月 11 日
編集済み: Stephen23 2019 年 1 月 11 日
Hi All,
I want to use fprintf for 6 double arrays and 2 date vectors. The dates will be at the first and second column and double arrays will come after. All of the arrays are 48x1 so I want them to get placed in 48 rows and 8 columns as a shape of 48x8 table. And also I want their headers on top. Headers are char as well. I wrote the code below but it gives very messy table.
filename = 'Results.csv';
fid = fopen(filename, 'wt');
if fid ~= -1
fprintf(filename,'%6s', column_headers);
for row = 1 : length(M)
fprintf(fid, '%s %12.4f %12.4f %d %d %d %d %d %d \n', char(date1(row,:)),char(date2(row,:)), dataRes(row), M(row), M2(row), M3(row),M4(row),MWDif(row));
end
fclose(fid);
end
Thanks in advance.
  1 件のコメント
dpb
dpb 2019 年 1 月 11 日
printf(filename,'%6s', column_headers);
for row = 1 : length(M)
fprintf(fid, '%s %12.4f %12.4f %d %d %d %d %d %d \n',
You created header row with only 6 columns widths and then wrote data of:
length(date format) 12 12 five_variable_width
Use counted widths for every column, including what is needed for spacing. There are examples with fprintf of similar idea.
BTW a convenient ML idiom in creating format strings for repeated variables is
fmt=['%14s' repmat('%12.4f', 1,2) repmat('%6d',1,6) '\n'];
or similar

サインインしてコメントする。

採用された回答

Stephen23
Stephen23 2019 年 1 月 11 日
編集済み: Stephen23 2019 年 1 月 11 日
Your format string does not match your data. In your question you describe and show 2 char variables and 6 numeric variables, but in your format string you have:
'%s %12.4f %12.4f %d %d %d %d %d %d \n'
% 1 -> one char format.
% 1 2 3 4 5 6 7 8 -> eight numeric formats.
Your code with some changes:
fnm = 'Results.csv';
[fid,msg] = fopen(fnm,'wt');
assert(fid>=3,msg) % better than |if|
fmt = '%s %s %s %s %s %s %s %s\n'; % 8 char, for header.
fprintf(fid,fmt,column_headers); % Does this work? Maybe you need to change this.
fmt = '%s %s %d %d %d %d %d %d\n'; % 2 char, 6 numeric.
for k = 1:numel(M)
fprintf(fid, fmt, char(date1(k,:)),char(date2(k,:)),dataRes(k),M(k),M2(k),M3(k),M4(k),MWDif(k));
end
fclose(fid);
  1 件のコメント
Omer Yasin Birey
Omer Yasin Birey 2019 年 1 月 11 日
Thank you Stephen that worked! You were also right about the line column_headers I changed it.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeCharacters and Strings についてさらに検索

タグ

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by