Average data in an array based on corresponding time values

5 visualizaciones (últimos 30 días)
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?

Respuesta aceptada

Star Strider
Star Strider el 26 de Nov. de 2018
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

Más respuestas (1)

Peter Perkins
Peter Perkins el 27 de Nov. de 2018
Star Strider's solution is old school. Nothing wrong with that, it gets the job done, but many people find accumarray hard to fathom. Here's another approach that uses timetables, which you may find makes other things easier:
>> t = [3;1;5;6;2;1;3];
>> d = [352;59592;5783;27;6849;264;284];
>> tt = timetable(d,'RowTimes',seconds(t))
tt =
7×1 timetable
Time d
_____ _____
3 sec 352
1 sec 59592
5 sec 5783
6 sec 27
2 sec 6849
1 sec 264
3 sec 284
>> ttAvg = retime(tt,'secondly','mean') % one way
ttAvg =
6×1 timetable
Time d
_____ _____
1 sec 29928
2 sec 6849
3 sec 318
4 sec NaN
5 sec 5783
6 sec 27
>> ttAvg = varfun(@mean,tt,'GroupingVariable','Time') % another way
ttAvg =
5×2 timetable
Time GroupCount mean_d
_____ __________ ______
1 sec 2 29928
2 sec 1 6849
3 sec 2 318
5 sec 1 5783
6 sec 1 27

Categorías

Más información sobre Logical en Help Center y File Exchange.

Productos


Versión

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by