muaaQ
muaaQ

Reputation: 39

Matlab Writing a matrix to text file issue

I am trying to correctly display a 25x5 column matrix under its "column headers" (5 of them) into a text-file.

fprintf(fileID,'%8s %16s %24s %32s %40s\n', 'ID', 'Column 1', 'Column 2',...
'Column 3', 'Column 4');
fprintf(fileID,'%8.1f %16.1f %24.1f %32.1f %40.1f\n', uData);

In the text-file, it is displaying one of the columns across the row like this (e.g. the ID column):

ID    Column 1    Column 2   Column 3    Column 4
1            2           3          4           5 

What it should be doing is going down the "ID" column, as 1, 2, 3, 4 and 5 all belong to one column, and I designate that as "ID" in the text file:

ID    Column 1    Column 2   Column 3    Column 4
1          ...          ...       ...         ...
2          ...          ...       ...         ...
3          ...          ...       ...         ...
4          ...          ...       ...         ...

Note that ... symbolises here that there is data there (the other values in the matrix).

So how may I fix it so that the matrix appears correctly?

Upvotes: 1

Views: 628

Answers (1)

rayryeng
rayryeng

Reputation: 104555

That's because when you write data using fprintf in MATLAB, the data is written in column-major format. That means the values of your matrix are printed to file such that each row of your matrix is actually written in the columns instead, which is what you're noticing. Notice that the values of 1, 2, 3, 4... are written along the columns first, where you desire the values to be written along the rows.

To write this in row-major (i.e. what you desire), you need to transpose your data prior to writing. Therefore, do this:

fprintf(fileID,'%8s %16s %24s %32s %40s\n', 'ID', 'Column 1', 'Column 2',...
'Column 3', 'Column 4');
fprintf(fileID,'%8.1f %16.1f %24.1f %32.1f %40.1f\n', uData.'); %// CHANGE - notice uData

Upvotes: 2

Related Questions