fprintf command issue. tricky columns.
Ältere Kommentare anzeigen
a=1:5;
b=90:94;
fprintf('Variables A : %.f | Variables B : %.f\n',a,b);
Consider the script above.
Variable a are the small values. I want to print all the variables on the LEFT COLUMN. Then variable b on the RIGHT column.
However with this sequence of fprintf the variable a results in an entirely different order.
1 2
3 4
5 90
91 92
93 94
Akzeptierte Antwort
Weitere Antworten (1)
Burners
am 1 Okt. 2012
6 Kommentare
Walter Roberson
am 1 Okt. 2012
Honglei's technique is the correct one when you are starting with row vectors:
fprintf('%f %f\n', [a;b])
If you are starting with column vectors then
fprintf('%f %f\n', [a,b].')
I have the exact same problem as Burners. Even when using the code as suggested in this answer it seems that Matlab takes the first column of the data and fills all the available slots in the first few rows of the .txt file, then moves on to the second column etc. In other words the data is read from the variable column by column and added to the .txt file row by row.
For example: a matrix has [1 2 3 ; 1 2 3 ; 1 2 3; 1 2 3], but it is written to my text file as [1 1 1; 1 2 2; 2 2 3; 3 3 3].
I want to have an output file that has the same structure as the data.
Walter Roberson
am 6 Okt. 2017
>> M = [1 2 3 ; 1 2 3 ; 1 2 3; 1 2 3]
M =
1 2 3
1 2 3
1 2 3
1 2 3
>> fprintf('%f %f %f\n', M.'); %notice the transpose
1.000000 2.000000 3.000000
1.000000 2.000000 3.000000
1.000000 2.000000 3.000000
1.000000 2.000000 3.000000
Diaa
am 7 Sep. 2019
why is it not written in the documentation? or was it?
Walter Roberson
am 7 Sep. 2019
fprintf(fileID,formatSpec,A1,...,An) applies the formatSpec to all elements of arrays A1,...An in column order, and writes the data to a text file.
If you have R2016b or later you might also want to look at compose(), which does not have this same behaviour.
Rik
am 7 Sep. 2019
The fundamental point is that Matlab arrays are column-based. We might read row by row when we look at an array to be written, but Matlab doesn't. Maybe there should be a warning to this effect in the doc, but as far as I'm aware there isn't. If you want to avoid ambiguous situations, you should provide each input as a separate array.
Kategorien
Mehr zu Low-Level File I/O finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!