Search code examples
csvfileprintfoctave

How to create a file with headers and different variables in Octave?


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?


Solution

  • 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]);