Keep trailing zeros in an output file.
41 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Peter Bohn
el 26 de Nov. de 2024 a las 2:05
Comentada: Peter Bohn
el 26 de Nov. de 2024 a las 4:37
This sounds like a stupid question, but i can't seem to find the answer anywhere.
I am outputting a text file from an array and in order to keep my columns aligned, i would like to keep trailing zeros of the values in the array.
I've attached what my output file currently looks like.
SpecData(:,1) = round(SpecData(:,1), 9, 'significant');
SpecData(:,2) = round(SpecData(:,2), 4, 'significant');
SpecData(:,3) = round(SpecData(:,3), 7, 'significant');
SpecData(:,4) = round(SpecData(:,4), 7, 'significant');
name = [numMonth2str(str2num(month))+year];
name_out = [F_out+name+type];
writematrix(SpecData,name_out,'Delimiter','tab');
for reference, column 1 of SpecData is a datenumber (these are causing an issue because some have 3 decimal places, and some have none, and column 2 is values ranging from 0.1000 to 6.0 and column 3 is between -500.00 to 500.00 approximately...
0 comentarios
Respuesta aceptada
Walter Roberson
el 26 de Nov. de 2024 a las 2:55
You can use dlmwrite with a 'precision' option. However, there is no option to adjust the precision per-column.
If you need different precision for different columns, then use compose with a format specified as a double-quoted string, and use writelines to write the resulting string array to a file.
1 comentario
Más respuestas (1)
praguna manvi
el 26 de Nov. de 2024 a las 4:18
Editada: praguna manvi
el 26 de Nov. de 2024 a las 4:20
As I see, you are looking to write a matrix to a tab-delimited text file with different precision values for each column. Since "writematrix" writes out numeric data as unquoted text, you can use "writecell" with "compose" to specify the formatted precision for each column as a string, as shown below:
% Input array with trailing zeros
SpecData = [
738000.123, 0.1, 123.456 123.456789, 0, 0;
738001.0, 1.125 13.52011 0.1234567, 0, 0;
738002.456, 0.1000, 500.00 456.7890123, 0, 0;
738476 1.207 21.9688 0.2504902 0 0
];
% Define the format for each column
formats = {'%.3f', '%.4f', '%.2f', '%.7f', '%.1f', '%.1f'};
% Apply formatting to each column using arrayfun and cellfun
formattedData = arrayfun(@(col) compose(formats{col}, SpecData(:, col)), 1:size(SpecData, 2), 'UniformOutput', false);
% Concatenate the formatted columns into a cell array
formattedData = horzcat(formattedData{:});
% Write the formatted data to a file using writecell
name_out = 'formatted_output.txt';
writecell(formattedData, name_out, 'Delimiter', '\t');
% Display the formatted data
disp('Formatted Data:');
disp(formattedData);
Ver también
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!