Issues with order that fprintf prints data

5 visualizaciones (últimos 30 días)
Peyton Jay
Peyton Jay el 22 de Mzo. de 2021
Comentada: Peyton Jay el 22 de Mzo. de 2021
I am trying to print a matrix to a .txt file using fprintf. The code I have written looks like this:
fprintf(fileName,'Header\r\n\r\n');
fprintf(fileName,'%f %f\r\n',matrix);
The matrix looks something like this:
matrix = 1 1
2 2
3 3
I want the code to print out exactly what is in the matrix, but instead it is going down each collumn to populate the rows in the text file, like this:
Header
1 2
3 1
2 3
Any ideas as to why this is occuring?

Respuesta aceptada

Cris LaPierre
Cris LaPierre el 22 de Mzo. de 2021
Editada: Cris LaPierre el 22 de Mzo. de 2021
MATLAB stores the data in column-major order by default. The simplest way is to address this is to transpose matrix.
matrix = [1 1; 2 2; 3 3];
fprintf('%f %f\r\n',matrix');
1.000000 1.000000 2.000000 2.000000 3.000000 3.000000
You might also consider using writetable (includes table variable names) or writematrix. It could simplify your code, and will handle writing a table/matrix as expected.
  3 comentarios
Cris LaPierre
Cris LaPierre el 22 de Mzo. de 2021
What do your headers look like?
If they could be variable names, consider using a table. Try this example.
matrix = [1 1; 2 2; 3 3];
Tmatrix = array2table(matrix);
Tmatrix.Properties.VariableNames = ["Apples","Oranges"]
Tmatrix = 3×2 table
Apples Oranges ______ _______ 1 1 2 2 3 3
With the data formatted correctly as a table, now use writetable(Tmatrix,filename,'Delimiter'," ") to create your file.
Peyton Jay
Peyton Jay el 22 de Mzo. de 2021
That does it, thank you!

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Data Type Conversion en Help Center y File Exchange.

Etiquetas

Productos


Versión

R2020a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by