How to save data in a formatted text file

6 views (last 30 days)
Alex on 2 Dec 2016
Edited: Alex on 2 Dec 2016
I have 2 vectors and an array that I need to write into a text file in a particular format (to be read by another program). The first line of the text file is the header info, that contains (num_alts, starting alt, alt div, num lats, starting lat, lat division):
num_alts = 5;
num_lats = 1:1:3;
header = [5, 60.000000, 100.0000000, 3, 45.0000, 2.00000];
The next part of the text file are integers from 0 to the number of alts: alt_int=0:1:num_alts;
Next, for each num_lat (from header file), there is a vector of data (from an array) that needs to be printed num_lat1, data1, new row, num_lat2, data2, new row, num_lat3, data3. There may be multiple rows of data for each num_lat. There data* is a column in an array called 'ne_profiles' Here is an example of the output I require:
5 60.000000 100.0000000 3 45.0000 2.00000 0.0 1 2 3 4 5 1 45.0 1.00000000e+000 4.88660000e+010 6.43080000e+011 8.23960000e+010 .... 1.02960000e+10 2 47.0 1.00000000e+000 3.88660000e+010 5.43080000e+011 6.23960000e+010 .... 2.02960000e+10 3 49.0 1.00000000e+000 5.88660000e+010 4.43080000e+011 5.23960000e+010 .... 3.02960000e+10
A txt file of a larger formatted data set is also attached (test.txt).
I was thinking I could create a new variable and format it from previous variable, but then any unused cells of the array receive a value of 0, which messes up the formatting for the text file. There must be an easier way to save the text file with multiple variables(a vector for each numlat*/data*), specifying how it should be written (e.g. new line after each latitudes data)
%Format PRF file as a variable
%prf_file(1,1) = max(max(altitudes));%max altitude
prf_file(1,1) = length(altitudes); %number of alts 1000
prf_file(1,2) = min(min(altitudes));%starting alt 60 km
prf_file(1,3) = altitudes(2,1) - altitudes(1,1); %alt div 1 km
prf_file(1,4) = length(Latitude);% num lats,
prf_file(1,5) = min(min(Latitude));%starting lat,
prf_file(1,6) = Latitude(1,2) - Latitude(1,1);%lat division
prf_file(1,7:1:prf_file(1,1)+7) = 0:1:prf_file(1,1);
for i = 1:prf_file(1,4)%length(Latitude)
%j=i+1;%row index
prf_file(i+1,1) = i;
prf_file(i+1,2:length(altitudes)+1) = ne_profiles(1:length(altitudes),i);
save('mytest_PRF.txt', 'prf_file', '-ASCII','-append');
Any suggestions would be appreciated.
Best regards,

Answers (0)


Find more on Data Import and Export in Help Center and File Exchange


Community Treasure Hunt

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

Start Hunting!

Translated by