Averaging sequential data if values are the same?
1 次查看(过去 30 天)
显示 更早的评论
I want to be able to average the values of an array of n rows and 5 columns, based on the repeated values of a specific column.
I only want to average the values that are next to each other and not all that repeat. Such that:
%Original data:
key_column = [-6 -6 -6 -6 -5 -5 -3 -3 -3 -1 -1 -1 0 0 1 1 2 2 2 3 3 5 5 5 5 6 6 6 6 4 4 4 3 3 3 3 3 3 3 2 2 2 1 1 1 1 0 0 -1 -1 -2 -3 -5 -5 -5 -5 -5 -5 -5 -6 -6 -6];
%Ends up as:
key_column_avg = [-6 -5 -3 -1 -0 1 2 3 5 6 4 3 2 1 0 -1 -2 -3 -5 -6]
I'm running into trouble because the values of the repeated numbers appear at multiple points in the column and I only want the to be averaged if they are "next to each other" on the column. Also, I'm having issues because the number of repeated values isn't the same for each number. Sometimes the value repeats for 10 times, sometimes for 3, sometimes for 7, sometimes for 4.
Is it possible to do this?
Thank you.
采纳的回答
Andrei Bobrov
2017-8-10
key_column_avg = key_column(diff([0,key_column(:)'],1,2) ~= 0);
4 个评论
Andrei Bobrov
2017-8-10
编辑:Andrei Bobrov
2017-8-10
d = data_example;
g = cumsum(diff([0;d(:,4)]) ~= 0);
out = splitapply(@mean,d,g);
or
d = data_example;
g = cumsum(diff([0;d(:,4)]) ~= 0);
[gg,c] = ndgrid(g,1:size(d,2));
out1 = accumarray([gg(:),c(:)],d(:),[],@mean);
更多回答(2 个)
José-Luis
2017-8-10
key_column = [-6 -6 -6 -6 -5 -5 -3 -3 -3 -1 -1 -1 0 0 1 1 2 2 2 3 3 5 5 5 5 6 6 6 6 4 4 4 3 3 3 3 3 3 3 2 2 2 1 1 1 1 0 0 -1 -1 -2 -3 -5 -5 -5 -5 -5 -5 -5 -6 -6 -6];
result = [key_column(diff(key_column) > 0), key_column(end) ]
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!