MATLAB: Average data in an array based on corresponding time values

averageaverage datadataMATLABmean

Hi there:
Let's say I have an array t = [3,1,5,6,2,1,3] and a corresponding data array d = [352,59592,5783,27,6849,264,284]. I want to average all of the values in d that correspond to the values in t. For example, when t = 1, I want to average 59592 and 264. Then, I want a new array t1 = [1,2,3,5,6] to correspond to the averages that were computed for each time and stored in a new array, d1. This is just a smaller example for a larger dataset.
This is what I'm trying to do right now:
for hour_to_test = 0:23
for i=1:length(t)
if t(i) == hour_to_test
temp = [temp, d(i)];
n = mean(temp);
d1 = [d1,n];
end
temp = [ ];
end
end
But this doesn't seem to be averaging all of the values for each hour. I am getting an array out of this loop that is the same length at d, not a length of 24. How do I go about fixing this?

Best Answer

Try this:
t = [3,1,5,6,2,1,3];
d = [352,59592,5783,27,6849,264,284];
[tu,~,ix] = unique(t);
dmeans = accumarray(ix, d, [], @mean);
d1 = [tu(:), dmeans]
d1 =
1 29928
2 6849
3 318
5 5783
6 27