saving matrix using fprintf in .txt file with different formatSpec
4 views (last 30 days)
Show older comments
sermet OGUTCU
on 8 Oct 2021
Commented: Star Strider
on 9 Oct 2021
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.
0 Comments
Accepted Answer
Star Strider
on 8 Oct 2021
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.')
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 Comments
More Answers (0)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!