Issues with order that fprintf prints data
5 次查看(过去 30 天)
显示 更早的评论
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?
0 个评论
采纳的回答
Cris LaPierre
2021-3-22
编辑:Cris LaPierre
2021-3-22
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');
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 个评论
Cris LaPierre
2021-3-22
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"]
With the data formatted correctly as a table, now use writetable(Tmatrix,filename,'Delimiter'," ") to create your file.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Data Type Conversion 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!