MATLAB: How to get and write data from text file

command linedatalooptext file

Text file as follows:
  • A column: Year (1998:1:2017)
  • B column: Day of the year (1:1:365 or 366)
  • C column: Hour
1998 152 1 30 25 12.5
1998 152 1 30 30 12
1998 152 1 30 35 11.8
1998 152 1 30 40 11.9
1998 152 1 30 45 12
I would like to get data but I have problem for leap year of 366 days. I'd like to extract all rows and then write data to text file, which is D= 30 and E=25 and B>=152 and B<=243 but it changes B>=153 and B<=244 according to leap years. I tried something but I got 0 and 1. How can I write text file what I want?
load fulltable.txt;
yearlenght = 365+(eomday(fulltable(:,1),2) == 29);
if fulltable(:,1) == yearlenght;
test = fulltable(fulltable(:,2)>=153 & fulltable(:,2)<=244 & fulltable(:,4)==30 & fulltable(:,5)==25,:);
else fulltable(:,1) ~= yearlenght;
test = fulltable(fulltable(:,2)>=152 & fulltable(:,2)<=243 & fulltable(:,4)==30 & fulltable(:,5)==25,:);
end

Best Answer

This code sorts the file data into one cell array C, where each cell in C contains the summer data for one year. The summer start and end dates are adjusted for the leap years.
mat = dlmread('fulltable.txt');
ily = (mod(mat(:,1),4)==0&mod(mat(:,1),100))|~mod(mat(:,1),400); % leap year.
idx = mat(:,2)>=(152+ily) & mat(:,2)<=(243+ily); % summer start and end dates.
idr = find(idx);
idg = cumsum([true;diff(idr)~=1]); % years into group numbers.
idz = find(mat(:,4)==30 & mat(:,5)==25); % match D and E column data.
fun = @(r){mat(intersect(r,idz),:)};
C = accumarray(idg,idr,[],fun);
And checking the start and end dates by looking at the first and last few rows of some of the cells:
>> C{1}(1:4,:)
ans =
1998 152 1 30 25 12.5
1998 152 3 30 25 10.9
1998 152 5 30 25 9.6
1998 152 7 30 25 8.4
>> C{1}(end-3:end,:)
ans =
1998 243 17 30 25 34.6
1998 243 19 30 25 32.5
1998 243 21 30 25 29.4
1998 243 23 30 25 20.5
>> C{3}(1:4,:)
ans =
2000 153 1 30 25 29.6
2000 153 3 30 25 25.4
2000 153 5 30 25 20.8
2000 153 7 30 25 15.7
>> C{3}(end-3:end,:)
ans =
2000 244 17 30 25 44.3
2000 244 19 30 25 44.8
2000 244 21 30 25 37.4
2000 244 23 30 25 29.5
You can then simply loop over the cells of the that cell array and export the data in files. Read the documentation to know how to access data in a cell array and save sequential files: