MATLAB: Print Data to .txt Files

fopenprintsprintftext filetxt

I have some problems on printing a whole data I have into a form of txt file. It consists of 5 variables and each variable is 3116×1 double. This is the script I made.
file_out2 = fopen(sprintf('%s%s%s', dir_in, name_file(8:11), '.txt'), 'w');
fprintf(file_out2, ' MJD_gab lat_gab SSH_gab SLA_gab YYF_gab\n');
fprintf(file_out2, '%14.8f %10.6f %10.4f %9.4f %16.8f\n', MJDgab, latgab, SSHgab, SLAgab, YYFgab);
fclose(file_out2);
In the first trial, the result came out but the variables were not printed into coloumn. It seems like they were printed 'horizontally'.
And everytime I ran the script for the second or manymore time, it always came error.
Perhaps it will work better if the script was corrected. I hope someone can help me out of this. Thank you for the help!

Best Answer

Put square brackets around the variables in your fprintf statement to concatenate them into a matrix, then transpose the matrix.
This should work:
fprintf(file_out2, '%14.8f %10.6f %10.4f %9.4f %16.8f\n', [MJDgab, latgab, SSHgab, SLAgab, YYFgab]');
If you have R2013b or later, an easier way would be to form a table from your data:
T5 = table(MJDgab, latgab, SSHgab, SLAgab, YYFgab, 'VariableNames',{'MJD_gab','lat_gab','SSH_gab','SLA_gab','YYF_gab'})
then use the writetable (link) function.