write data into a file line by line inside foef(fid) loop
1 view (last 30 days)
Show older comments
Hi,
I need to read data from .txt file line by line and then for each line I have to call a function (function takes single value each for all inputs at a time and gives the output with dimension 1x3) and save it. Then, it "ll read 2nd line, call function and save it as nextline in file. Same for 3rd lines and so on. The function works fine for 1st line, from 2nd lines it shows error (it is because function takes only a single value each for all inputs). Can anyone help. Thank you so much. My code is below.
clear all;clc;
fid=fopen('testfile.txt','r');
fid1 = fopen('test.txt', 'wt');
i = 0;
while ~feof(fid);
i;
%%%get data
line = fgetl(fid);
ms=line(1:10);t=line(12:23);
alt(i+1)=str2num(line(29:38))*1e-3;%m to km
lon(i+1)=str2num(line(41:47));
lat(i+1)=str2num(line(49:55));
lst(i+1)=str2num(line(57:62));
dens(i+1)=str2num(line(72:88))*1e-3;%kgm-3 to gcm-3
%%convert to ut
ut(i+1)= rem(datenum(t),1)*24;
sec(i+1)=ut(i+1)*3600;
%convert to doy
dt(i+1)=datetime(ms, 'ConvertFrom','datenum');
doy(i+1)=day(dt(i+1),'dayofyear');
%%assume some year, f107a,f107 and ap for testing
year(i+1,:)=2000;
f107a(i+1,:)=150;f107(i+1,:)=150;ap(i+1,:)=4;
%%call function
%%function takes single value of each input paramaters at a time
%%outputn has dimension of 1x3
[outputn]=nrlmsise00_code(doy,year,sec,alt,lat,lon,lst,f107a,f107,ap);
%%normalize data
densn1(i+1)=dens(i+1)*outputn(2)/outputn(1);
densn2(i+1)=dens(i+1)*outputn(3)/outputn(1);
new_data=[densn1 densn2 outputn];
%%save file
fprintf(fid1,'%d %d %d %d %d\n',new_data);
i = i+1;
end;
fclose(fid);fclose(fid1);
0 Comments
Answers (1)
KSSV
on 28 Jul 2022
I would first read the complete file and then run loop for each line.
T = readtable('https://in.mathworks.com/matlabcentral/answers/uploaded_files/1080015/testfile.txt')
You can access the column you want by using T.(1), T.(2), T.(3) etc.
5 Comments
See Also
Categories
Find more on Convert Image Type 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!