Writing Matlab Table to File
Ältere Kommentare anzeigen
I am trying to find an easy way to print nicely-formatted tables to a text file. By "nicely-formatted," I mean the way that tables are displayed in the console (with spacing and column headers; see the example below). I was hoping 'fprintf' would do the trick, but this gives me an error. Surely there has to be a way?
>> names = ["Column 1", "Column 2"];
>> S = table([0; 1; 2; 3], [6; 4; 3; 7], 'VariableNames', names);
>> disp(S);
Column 1 Column 2
________ ________
0 6
1 4
2 3
3 7
>> file = fopen("newfile.txt", 'w');
>> fprintf(file, S);
Error using fprintf
Invalid format.
Note: There is a function 'writeTable,' but that produces raw data files (eg. comma delimited files), which isn't what I want.
1 Kommentar
Gabriel
am 4 Nov. 2026 um 16:46
I know it's old but thank you very much. I was searching for this for a while.
Antworten (2)
First of all, you are using fprintf incorrectly, and thankfully all MATLAB errors are quite intuitive. This one tells you, you've forgotten to define a format for fprintf. For more info, see the function help.
Next, you've also missed to read writetable help; otherwise you would figure it out that the function allows you to set the delimiter.
S = table([0; 1; 2; 3], [6; 4; 3; 7], 'VariableNames', {'col1', 'col2'});
% write to a tab delimited file
writetable(S, 'newfile.txt', 'delimiter', '\t')
% check it
type newfile.txt
col1 col2
0 6
1 4
2 3
3 7
% read it again in MATLBA
Snew = readtable('newfile.txt')
col1 col2
____ ____
0 6
1 4
2 3
3 7
1 Kommentar
Paschalis Economou
am 27 Dez. 2020
Jeff Miller
am 27 Sep. 2023
Try this:
str = formattedDisplayText(S);
str = erase(str,"<strong>");
str = erase(str,"</strong>");
fprintf(file,"%s",str);
2 Kommentare
Rather than suppressing the formatting text manually, specify the SuppressMarkup name-value argument.
A = array2table(magic(3))
s1 = formattedDisplayText(A)
hasStrong1 = contains(s1, "strong")
s2 = formattedDisplayText(A, SuppressMarkup=true)
hasStrong2 = contains(s2, "strong")
T = table([0; 1; 2; 3], [6; 4; 3; 7], 'VariableNames',["Column 1", "Column 2"])
S = formattedDisplayText(T)
writelines(S,'test.txt')
type test.txt
Kategorien
Mehr zu Text Data Preparation finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!