Strange file output while using fprintf
2 次查看(过去 30 天)
显示 更早的评论
Hi Everyone, thank you in advance for your help. I'm trying to write two columns in a txt file using fprintf.
fprintf(filesave2,'%d %\r\n', X, Y);
I even tried manipulating the numbers of characters i wanted to print:
fprintf(filesave2,'%3d %7.5f\r\n', X, Y);
but all in vain. It keeps giving me very strange results.
Results:
9 9.00000
9 9.00000
9 9.00000
..... and so on.
My original data
looks like this:
X is a vector from 5 to 300 with intervals of 5. i.e. 5 10 15 ... 300
Y is a vector with power values 0.46957 0.41538 0.37951 .. etc (60 values).
How can i fix this? So that the written file looks like:
5 0.46957
10 0.41538
15 0.37951
...
etc
Thank you so much for your help!
0 个评论
采纳的回答
Walter Roberson
2013-4-3
fprintf(filesave2,'%d %f\r\n', [X(:), Y(:)].' );
3 个评论
Walter Roberson
2013-4-3
编辑:Walter Roberson
2013-4-3
Please re-check that X and Y have exactly the same number of elements. Whether they are row vectors or column vectors or matrices does not matter for the code I gave, as long as the number of them is the same.
The .' is matrix transpose. The first part, [X(:), Y(:)] is forming an array of two columns, X and Y, and the .' flips that around so that X becomes the first row and Y becomes the second row. You need to do this for your fprintf() because fprintf() follows values down the columns -- so you want the first column to have an X value and then a Y value (to print them side by side), and the next column to have the second X and Y values, and so on.
If you knew for sure that X and Y are row vectors, then you could instead have coded as
fprintf(filesave2,'%d %f\r\n', [X;Y] );
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Install Products 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!