I wrote the data of the plot in a .dat file but when plotting the same file the graph is not the same

5 vues (au cours des 30 derniers jours)
I used the following code to read the data from a data file and store it in another data file but when plotting both are different
Mz = fopen('time11.dat','w');
S = dlmread('time_1.dat');
fprintf(Mz,'%f\t%f\n',S(:,1),S(:,2));
figure
plot(S(:,1),S(:,2));
fclose(Mz);

Réponse acceptée

Walter Roberson
Walter Roberson le 13 Fév 2020
fprintf(Mz,'%f\t%f\n',S(:,1:2).');
  3 commentaires
Walter Roberson
Walter Roberson le 13 Fév 2020
When you use fprintf(), MATLAB outputs all of the first output parameter in linear order, and does not go on to the second output parameter until the first one is finished. So your
fprintf(Mz,'%f\t%f\n',S(:,1),S(:,2));
does not mean to output S(1,1), S(1,2) on the same line, then S(2,1), S(2,2) on the next line, S(3,1), S(3,2) and so on. Instead, it means to output S(1,1), S(2,1) that would go on the first line, then S(3,1), S(4,1) would go on the second line, and so on. Eventually S(:,1) would be exhausted and it would start outputing S(1,2), S(2,2), S(3,2) and so on.
When you use
fprintf(Mz,'%f\t%f\n',S(:,1:2).');
then S(:,1:2) is the same linear order as what I described earlier, S(1,1), S(2,1), S(3,1) and so on and then S(1,2), S(2,2), S(3,2) and so on. But notice the .' transpose operator, which flips the array from
S11 S12
S21 S22
S31 S32
... ...
to become in memory
S11 S21 S31 S41 ...
S12 S22 S32 S42 ...
In this matrix, in linear memory order, S11 is first, then S12, then S21, then S22, S31 then S32, and so on. So when fprintf asks for items, the first thing output is S11, then S12, then S21 S22 -- the output is effectively across the rows of the array where without the .' it was down the columns first.
This turns out to be a quite important trick in MATLAB for using fprint with a vector of values: you are fairly likely to end up using a .' operator to get data into the right order for fprintf to print.
Now, if you just happen to have your data as row variables, S1, S2, then you could write it thinking about column order, as [S1.', S2.'] to create two concatenated columns, and then .' the result -- [S1.', S2.'].' in order to feed it to fprintf in the right order. But it happens that in this case you can instead just use [S1; S2] without any transposes. It is a little outside of our expectations of how things should work, but it does feed the data to fprintf() in the order it needs.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Graphics Performance dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by