extracting data from a file and creating a file.
2 views (last 30 days)
Show older comments
How should the matlab code be, which reads the times corresponding to the given station names (for example C0AU3SZ IP, c0ATYSZ IP ....)from the data files we have and save them into a single file. T
he sample file is as follows.
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1159523/image.jpeg)
Answers (1)
Amit Dhakite
on 8 Jun 2023
Hi Yeliz,
According to my understanding, you want to read station names and their corresponding times from multiple files.
You can refer to the following example to get started, which reads data from one file "data_in.txt":
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1406159/image.png)
And saves the required information in the file "data_out.txt":
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1406164/image.png)
Here is the code snippet:
% Open the text file
fid = fopen('data_in.txt', 'r');
% Read the first line and split station names and times
header = fgetl(fid);
header = split(header, ' ');
stations = header{1};
times = header{2};
% Initialize arrays to hold station names and times
stationNames = {};
stationTimes = {};
% Loop through the rest of the lines and extract station name and time
while ~feof(fid)
line = fgetl(fid);
pieces = split(line, ' ');
stationNames{end+1} = pieces{1};
stationTimes{end+1} = pieces{2};
end
% Close the file
fclose(fid);
% Save the station names and times to a new file
fidNew = fopen('data_out.txt', 'w');
fprintf(fidNew, '%s %s\n', stations, times);
for i=1:length(stationNames)
fprintf(fidNew, '%s %.2f\n', convertCharsToStrings(stationNames{i}), convertCharsToStrings(stationTimes{i}));
end
% Close the new file
fclose(fidNew);
For further information related to the functions used above, kindly refer to the following links:
- fopen(): https://www.mathworks.com/help/matlab/ref/fopen.html
- fgetl(): https://www.mathworks.com/help/matlab/ref/fgetl.html
- split(): https://www.mathworks.com/help/matlab/ref/split.html
- feof(): https://www.mathworks.com/help/matlab/ref/feof.html
- fclose(): https://www.mathworks.com/help/matlab/ref/fclose.html
- fprintf(): https://www.mathworks.com/help/matlab/ref/fprintf.html
- convertCharsToStrings(): https://www.mathworks.com/help/matlab/ref/convertcharstostrings.html
0 Comments
See Also
Categories
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!