How to use accumarray?
Show older comments
Accepted Answer
More Answers (2)
Kelly Kearney
on 18 Nov 2014
A small variation in Guillaume's suggestion, in case you want a value for every day/hour/hour of day (even if no data was collected then). In this case, you can specify the expected output size and fill value:
data = [datevec(now + sort(rand(1000,1)*60)) rand(1000,4)];
dn = datenum(data(:,1:6));
day = floor(dn);
hr = floor(dn * 24);
hrofday = floor((dn - floor(dn))*24);
didx = day - min(day) + 1;
daily = zeros(max(didx), 4);
for ii = 1:4
daily(:,ii) = accumarray(didx, data(:,6+ii), [max(didx) 1], @mean, NaN);
end
Kevin Claytor
on 18 Nov 2014
You could use a Table structure. First, I'd convert the first few elements to a datetime object , so that they're easier to work with. Using your example above;
mytime = [2008,1,5,15,8,0; 2008,1,6,15,8,0]; % Demo with different days
% mytime = data(:, 1:6); % Extract the date info from the data array
DateAndTime = datetime(mytime)
DateAndTime =
05-Jan-2008 15:08:00
06-Jan-2008 15:08:00
Now we can put everything into a table;
Zone1 = data(:, 7);
Zone2 = data(:, 8);
T = table(DateAndTime, Zone1, Zone2);
Now we can start to really have fun. Let's see what the consumption by hour looks like;
% First get the hour out of the datetime object and add it as a new column to our table
T.Hour = hour(T.DateAndTime);
% Now group the results by hour, summing all the values for a given hour;
EnergyByHour = varfun(@sum, T, 'InputVariables', 'Zone1', 'GroupingVariables', {'Hour'})
% And plot the results
plot(EnergyByHour.Hour, EnergyByHour.sum_Zone1)
Check out the docs for more example cases of hour you can use the Table format, and how to apply functions across the rows / columns of your tables to get exactly what you're after. It's a pretty neat data structure, although some of the function calls can be a bit opaque (like varfun above).
Categories
Find more on Tables 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!