saving matrix using fprintf in .txt file with different formatSpec

3 ビュー (過去 30 日間)
sermet OGUTCU
sermet OGUTCU 2021 年 10 月 8 日
コメント済み: Star Strider 2021 年 10 月 9 日
data=[2 0.232 0.333 0.421 0.111;3 0.111 0.252 0.385 0.600;4 0.500 0.620 0.100 0.210];
startingFolder='C:\Program Files\MATLAB';
if ~exist(startingFolder, 'dir')
startingFolder = pwd;
end
defaultFileName=fullfile(startingFolder, '*.txt');
[baseFileName, folder]=uiputfile(defaultFileName, 'Select a file');
if baseFileName == 0
return
end
fullFileName = fullfile(folder, baseFileName); %fullfile=building file
fid = fopen(fullFileName, 'w');
fprintf(fid, '%*s\n\n', 15, 'Clock_comparisons_uncorrected (** GPS **)');
fprintf(fid,'%*s %*s %*s %*s %*s\n',1,'PRN',1,' RMS(ns)', 1, 'RMS(m)', 1, 'STD(ns)', 1, 'STD(m)');
% ...
After the last line, I need to print data matrix in the txt file (after the PRN RMS(ns) RMS(m) STD(ns) STD(m) header) as following:
2 0.2320 0.3330 0.4210 0.1110
3 0.1110 0.2520 0.3850 0.6000
4 0.5000 0.6200 0.1000 0.2100
I tried the following codes, but formatSpec cannot be seperated for each column so the values of first columns are printed with three digits after the integer.
fmt = [repmat('%.3f ', 1, 4), '%.3f\n'];
fprintf(fid, fmt, data');
I also used the following code using different arrays for each column, but this time orders of columns and rows are not the same as the data matrix.
fprintf(fid,'%.0f %.3f %.3f %.3f %.3f\n',column_1, column_2, column_3,column_4,column_5);
My matlab version is 2019a.

採用された回答

Star Strider
Star Strider 2021 年 10 月 8 日
Try something like this —
data=[2 0.232 0.333 0.421 0.111;3 0.111 0.252 0.385 0.600;4 0.500 0.620 0.100 0.210];
fid = 1; % Standard Output For Simplicity
fprintf(fid,'%.0f %.3f %.3f %.3f %.3f\n', data.')
2 0.232 0.333 0.421 0.111 3 0.111 0.252 0.385 0.600 4 0.500 0.620 0.100 0.210
fclose(fid); % Remember To Close The File When You HJave Finished Writing To It (Or Reading From It)
Transpose ‘data’ then write using the statement.
There are much easier ways to write files, specifically writematrix and similar functions (such as csvwrite in older versions/releases).
.
  2 件のコメント
sermet OGUTCU
sermet OGUTCU 2021 年 10 月 9 日
Thanks a lot @Strider.
Star Strider
Star Strider 2021 年 10 月 9 日
As always, my pleasure!
.

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeApp Building についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by