Write a tabbed matrix in a txt file
7 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Francesco Cattaneo
el 30 de Abr. de 2021
Comentada: dpb
el 2 de Mayo de 2021
Hi everyone,
I need to write a numeric matrix in a text file, in such a way that each row is indented at the beginning.
Let's say I want a header and a matrix written below:
clear all
clc
A = [2 4 ; 5 3 ; 9 6 ; 6 4 ; 8 8];
test = fullfile("test");
[fid, error] = fopen(test, 'w');
fprintf(fid, "############\n");
dlmwrite(test, A, 'delimiter',"\t", '-append');
fclose(fid);
I would obtain a file "test" with:
############
2 4
5 3
9 6
6 4
8 8
Is there a way to write "test" like this?
############
2 4
5 3
9 6
6 4
8 8
Thank you for any kind of help
0 comentarios
Respuesta aceptada
dpb
el 30 de Abr. de 2021
Editada: dpb
el 30 de Abr. de 2021
Read the rest of the documentation for dlmwrite --
Name-Value Pair Arguments
...
'precision' — Numeric precision
(default) | scalar | C-style format specifier | character vector
dlmwrite(test, A, 'delimiter',"\t",'precision','%3d','-append')
Salt to suit...limitation is same format string for all variables; if you want/need more control, use fprintf and whatever formatting string you desire.
NB: dlmwrite is also deprecated in favor of writematrix beginning in R2019b, but the latter fails to provide the ability to specify a format string; you get whatever the 'long g' format returns for the given numeric data and so is not suitable replacement in terms of all functionality if must control the format.
6 comentarios
dpb
el 2 de Mayo de 2021
Well, you can do both if you add the width and precision...I didn't show; thought it would be evident
>> fprintf('%20.15g\t%20.15g\n',A.')
240.14 0.0031567
5 3
3.14159265358979 6
6 4
8 3.14159265358979e-08
>>
The file is then bigger thatn with just the '%.15g' because the alignment requires blank fill that you don't have with the variable field width.
Más respuestas (0)
Ver también
Categorías
Más información sobre Text Files en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!