Reputation: 17
I need to create a file with some variables and their corresponding headings. For this I created an array with the variables making them the same size. To save or create this file I have tried many things but they do not work properly. I tried first save blbl.txt V1 V2
, but I did not find the way to put headers. So I changed to fprintf
as I found in a Matlab forum (I didn't find an example like this in the Octave forums), however it does something different than in the examples shown.
V1 = [1 2 3];
V2 = [4 5 6];
V = [V1.' , V2.'];
fileID=fopen('Pin.txt','w');
fprintf(fileID,'%12s %13s\n','V1','V2');
fprintf(fileID,'%6.6f %13.6f\n',V);
fclose(fileID);
It prints the headers and the two columns but it prints first the values of V1
then the values in V2
. I mean:
V1 V2
1 2
3 4
5 6
and it should be (this is what supposedly happens in Matlab)
V1 V2
1 4
2 5
3 6
Does anyone understand why this is happening? Or if there is a better way to do this in Octave?
Upvotes: 0
Views: 1831
Reputation: 22225
What are you trying to do? It seems to me you are simply trying to create a csv file (well, with spaces instead of commas).
If that's the case, you could use csv-related functions. E.g.
pkg load io
C = vertcat( { 'V1', 'V2' }, num2cell( V ) );
cell2csv ( 'Pin.txt', C, ' ' );
In any case, the reason the output comes out in that way, as Luis also hinted, is the following (taken from the Matlab documentation)
If your function call provides more input arguments than there are formatting operators in the format specifier, then the operators are reused.
Since matlab and octave column-major-order (i.e. the next element is the one 'below', not the one 'to the right'), if you want to 'reuse' variables in this manner, you need to arrange things as Luis suggested.
If matlab produces the 'correct' result instead, then this is actually a matlab bug, since it should be doing it the same as octave in this case, and you shouldn't rely on it.
Upvotes: 0
Reputation: 112689
As usual in Matlab/Octave, fprintf
takes the values in column-major order. So you need to transpose V
:
fprintf(fileID, '%6.6f %13.6f\n', V.');
or
fprintf(fileID, '%6.6f %13.6f\n', [V1; V2]);
Upvotes: 2