write data into a file line by line inside foef(fid) loop

4 views (last 30 days)
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);

Answers (1)

KSSV
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')
T = 5×12 table
Var1 Var2 Var3 Var4 Var5 Var6 Var7 Var8 Var9 Var10 Var11 Var12 __________ ________ _______ __________ ______ _______ ______ ______ __________ __________ _____ _____ 2002-04-04 00:50:00 {'GPS'} 5.1873e+05 146.08 -56.598 10.516 303.54 1.3136e-12 1.241e-12 0 0 2002-04-04 00:50:10 {'GPS'} 5.1864e+05 146.07 -55.967 10.518 304.18 1.3165e-12 1.2409e-12 0 0 2002-04-04 00:50:20 {'GPS'} 5.1855e+05 146.06 -55.336 10.52 304.81 1.3144e-12 1.2408e-12 0 0 2002-04-04 00:50:30 {'GPS'} 5.1845e+05 146.06 -54.705 10.522 305.44 1.3145e-12 1.2407e-12 0 0 2002-04-04 00:50:40 {'GPS'} 5.1835e+05 146.04 -54.074 10.524 306.07 1.3198e-12 1.2406e-12 0 0
You can access the column you want by using T.(1), T.(2), T.(3) etc.
  5 Comments
Madan Kumar
Madan Kumar on 29 Jul 2022
Thank you so much. I am exploring readtable option but yet to succeed.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!