Spliting data based on date

How can we split data into sub arrays based on dates? Lets say we do have thousands data points for different dates (for a week) . I want to split this data into arrays based on the dates as the number of observations is changing from date to date. The following is a sample from my data. Many thanks in advance

 Accepted Answer

I'd extract the columns and use the unique() function on them
col1 = array(:, 1);
col2 = array(:, 2);
col3 = array(:, 3);
uniqueDates = unique(col1);
uniqueTimes = unique(col2);
Then use a for loop to find the index of the dates, and place the other two columns into a cell array. You need a cell array because you might possibly have different numbers of times for each date.
for k= 1 : length(uniqueDates)
thisDate = uniqueDates(k);
indexesWithThisDate = (col1 == thisDate);
% Extract all rows with this date and put into a cell array.
theseData = array(indexesWithThisDate, 2:3); % Get cols 2 and 3
% Assign to a new cell
ca{k} = theseData;
end
You might not need all of the lines in the first chunk of code. This code is untested, so be sure to use the debugger to step through it in the case of problems.

More Answers (2)

dpb
dpb on 23 Dec 2014
Convert to datenums and then make selections based on those...of course, convert the comparison dates to datenum as well.

3 Comments

Thank you. I Know I need to convert it using datenum. But I don't know how to write a correct matlab code to divide them according to the date. I tried a lot but I have no result.
Considering that you haven't even told us what form or format your dates are in, we don't know either. You say you've "tried a lot" but you didn't share any of those with us. What did you try? Can you provide any data? Have you read this yet?
Bido12
Bido12 on 23 Dec 2014
Edited: Bido12 on 23 Dec 2014
I'm sorry for that. This is a sample of my data. The first column is MATLAB date and Time format. I need to divide my data according to date. My data is for seven days.

Sign in to comment.

Most likely, you want to use the third return value unique on datenums or datevecs to find out how to split your data, and possibly accumarray to perform operations on the other columns.
For example:
data = [2014 12 19 1
2014 12 19 1.2
2014 12 20 2.2
2014 12 19 1.4
2014 12 20 2
2014 12 20 2.6
2014 12 20 2.4
2014 12 21 3.5]; %year month day value
[dates, ~, dateidx] = unique(data(:, 1:3), 'rows'); %find out where the dates go
dataperday = arrayfun(@(idx) data(dateidx==idx, 4), 1:size(dates, 1), 'UniformOutput', false)'; %split into cell arrays
averageperday = accumarray(rows, data(:, 4), [], @mean); %calculate mean per day
See also this answer

Asked:

on 23 Dec 2014

Commented:

on 23 Dec 2014

Community Treasure Hunt

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

Start Hunting!