Filter löschen
Filter löschen

Strange file output while using fprintf

1 Ansicht (letzte 30 Tage)
Hissam Aziz
Hissam Aziz am 3 Apr. 2013
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!

Akzeptierte Antwort

Walter Roberson
Walter Roberson am 3 Apr. 2013
fprintf(filesave2,'%d %f\r\n', [X(:), Y(:)].' );
  3 Kommentare
Walter Roberson
Walter Roberson am 3 Apr. 2013
Bearbeitet: Walter Roberson am 3 Apr. 2013
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] );
Hissam Aziz
Hissam Aziz am 3 Apr. 2013
Bearbeitet: Hissam Aziz am 3 Apr. 2013
Ahh fixed it! Worked like a charm!

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Install Products finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by