user3052817
user3052817

Reputation: 245

How do I grab only June, July, August daily data in Matlab from multi-year data using a for loop?

I have a 2 dimensional matrix [date x data]. The date is formatted in Matlab time, and spans 30+ years of data. I want to find only June, July, and August months of data. How do I loop through the date column to find all daily data for JJA months and create a new variable from it? The date column spans an entire year (Jan-Dec) from 1958-2014.

Sample data is as follows:

715290  248.466883960556
715291  283.505916006759
715292  324.290798860324
715293  330.142892431377
715294  267.062371422836
715295  263.568232655174
715296  540.856981589398
715297  1068.81389065867
715298  1174.92651788078
715299  1077.71223624073
715300  940.399428121956
715301  720.323217401065
715302  689.605704068148
715303  777.776178783704
715304  914.330565109213
715305  1069.02532264344
715306  1168.15631281824
715307  1263.47638011252
715308  1309.37995956891
715309  1318.50751550512
715310  1303.83817524424
715311  1273.11884252625
715312  1272.70005316829
715313  1330.08825971279
715314  1391.65459098343
715315  1511.13670010565
715316  1524.18921565080
715317  1451.41725782868
715318  1384.63128177358
715319  1388.90746497726
715320  1423.66479419858
715321  1417.13642861071

I've tried the following, but the indices ('idx' variable) doesn't successfully grab the Matlab date time column from the 'data' matrix:

t = datevec(data(:,1)); % get the date value 
[unDates, ~, subs] = unique(t(:,1:2),'rows'); % group by unique month
idx = find(unDates(:,2) == 6 | unDates(:,2) == 7 | unDates(:,2) == 8); %Find JJA months
time_JJA = unDates(idx); %unDates is a 2D matrix [YYYY x M]. Col 1 = year and Col 2 = month (e.g., '6' is June)

Upvotes: 0

Views: 332

Answers (1)

Finn
Finn

Reputation: 2343

I would always prefer to use the matlab datetime format, as i find it quite handy. Then you can use the special date operations and it get quite easy:

%creating datetimes
DataAsDatetime=datetime(data(:,1), 'ConvertFrom', 'datenum');
%getting a vector of month
DataMonth=month(DataAsDatetime);
%creating that logical vector
Logicalvector=(DataMonth==6 | DataMonth==7 | DataMonth==8);
%getting what you want
WhatYouWant=X(Logicalvector,2);
%or all of that in one line
WhatYouWant2=X(month(datetime(data(:,1), 'ConvertFrom', 'datenum'))>=6 & month(datetime(data(:,1), 'ConvertFrom', 'datenum'))<=8,2);

I would reccomend you to transform to datetime right after importing. It that case you can go even more into detail, like looking for weekdays or filtering specific years

Upvotes: 1

Related Questions