按分组数据中的窗口大小对数据求和(Summing data by window size in grouped data)

我是matlab的新手,我试图找到一种方法来完成以下任务而不使用for循环:

我有一个如下所示的数据集:

data = [1 5; 1 3; 1 8; 2 1; 2 2; 2 5; 3 3; 3 8; 3 4]

第一列是一个组(将来是一个月份组合)

现在我想计算具有给定窗口大小的第二列的总和,但仅当组索引相同时 - 如果不是,则应计算该组中的最大总和。

窗口大小= 2我想创建以下结果:

summed_data = [1 8; 1 11; 1 8; 2 3; 2 7; 2 5; 3 11; 3 12; 3 4]

窗口大小为3时,结果如下所示:

summed_data = [1 16; 1 11; 1 8; 2 8; 2 7; 2 5; 3 15; 3 12; 3 4]

等等。

我想通过创建足够的子索引来使用accumarray - 但我的窗口大小有问题,并且总和是重叠的。

有没有人知道如何在不使用循环的情况下实现它?

在此先感谢和最好的问候斯蒂芬

I am quite new to matlab and I am trying to find a way to accomplish the following task without using for loops:

I have a data set looking like this:

data = [1 5; 1 3; 1 8; 2 1; 2 2; 2 5; 3 3; 3 8; 3 4]

the first column is a group (being a month year combination in the future)

Now I want to calculate a sum over the second column with a given window size but only if the group index is the same - if not the maximal sum in this group shall be calculated.

With window size=2 I would like to create the following result:

summed_data = [1 8; 1 11; 1 8; 2 3; 2 7; 2 5; 3 11; 3 12; 3 4]

With a window size of 3 the result would look like this:

summed_data = [1 16; 1 11; 1 8; 2 8; 2 7; 2 5; 3 15; 3 12; 3 4]

and so on.

I thought about using accumarray by creating sufficient subindexes - but I have a problem with the window size and that the sums are overlapping.

Has anyone an idea on how to implement it without using loops?

Thanks in advance and best regards stephan

最满意答案

这似乎有效:

ws = 2; k = [ones(ws,1);zeros(mod(ws,2),1)]; C = accumarray(data(:,1),data(:,2),[],@(v){conv(v,k,'same')})

你似乎正在锚定窗口中的当前像素并向前看。 那是对的吗?

不确定这是否涵盖所有角落情况,但它可能会引导您朝着正确的方向前进。

测试:ws = 2

ws = 2; k = [ones(ws,1);zeros(mod(ws,2),1)]; C = accumarray(data(:,1),data(:,2),[],@(v){conv(v,k,'same')}); summed_data = [data(:,1) vertcat(C{:})] summed_data = 1 8 1 11 1 8 2 3 2 7 2 5 3 11 3 12 3 4

测试:ws = 3

summed_data = [data(:,1) vertcat(C{:})] summed_data = 1 16 1 11 1 8 2 8 2 7 2 5 3 15 3 12 3 4

This seems to work:

ws = 2; k = [ones(ws,1);zeros(mod(ws,2),1)]; C = accumarray(data(:,1),data(:,2),[],@(v){conv(v,k,'same')})

You seem to be anchoring to the current pixel in the window and looking forward. Is that correct?

Not sure if this covers all corner cases, but it might steer you in the right direction.

Test: ws = 2

ws = 2; k = [ones(ws,1);zeros(mod(ws,2),1)]; C = accumarray(data(:,1),data(:,2),[],@(v){conv(v,k,'same')}); summed_data = [data(:,1) vertcat(C{:})] summed_data = 1 8 1 11 1 8 2 3 2 7 2 5 3 11 3 12 3 4

Test: ws = 3

summed_data = [data(:,1) vertcat(C{:})] summed_data = 1 16 1 11 1 8 2 8 2 7 2 5 3 15 3 12 3 4

更多推荐

using,使用,电脑培训,计算机培训,IT培训"/> <meta name="description" co