Aggregation by index in first column
Mostrar comentarios más antiguos
Hi!
I have to aggregate some electricity consumption which is provided over a whole year in seconds. Nevertheless, a simple example may illustrate the purpose.
lets say i have day indexes as : a = ones(1,5); b = [2 2 2 2 2]; day = [a b a]'; daysize = size(day);
as day 1 will occur next month again and so on
and a consumption as :
consump = [1:daysize(1)]';
I want to sum up my consumption wherever the same index occurs as my day. Thus, my result should look like the following
result = [sum(consump(1:5)),sum(consump(5:10)),sum(consump(10:15))]'
Eventually, the final result should be :
aggregated_data = [[1 2 1]',result]
Appreciate your time! Cheers Frederik
3 comentarios
Jan
el 10 de En. de 2018
I stopped here already, because I did not get it:
day = [1, 2, 1; ...
1, 2, 1; ...
1, 2, 1; ...
1, 2, 1; ...
1, 2, 1];
daysize = size(day);
If this is the input, what does this explanation mean:
as day 1 will occur next month again and so on
?
Frederik Skøtt
el 10 de En. de 2018
Jan
el 10 de En. de 2018
I've overseen that days is a vector, not a matrix. See my 2nd answer.
Respuesta aceptada
Más respuestas (1)
Jan
el 10 de En. de 2018
Ah, I get it now. So the actual problem is to convert
days = [1 1 1 1 1 2 2 2 2 2 3 3 3 3 3 1 1 1 1]
to
days = [1 1 1 1 1 2 2 2 2 2 3 3 3 3 3 4 4 4 4]
Correct? Then accumarray solves the problem directly.
[~, N] = RunLength(days);
udays = RunLength(1:numel(N), N);
A = accumarray(udays, consump);
And without the fast C-mex RunLength:
x = days(:);
d = [true; diff(x) ~= 0]; % TRUE if values change
n = diff(find([d', true])); % Number of repetitions
udays = repelem(1:numel(n), n); % Need Matlab >= R2015a
A = accumarray(udays, consump);
3 comentarios
Frederik Skøtt
el 11 de En. de 2018
Editada: Frederik Skøtt
el 11 de En. de 2018
Frederik Skøtt
el 11 de En. de 2018
Frederik Skøtt
el 11 de En. de 2018
Categorías
Más información sobre Matrix Indexing en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!