Labfans是一个针对大学生、工程师和科研工作者的技术社区。 | 论坛首页 | 联系我们(Contact Us) |
![]() |
![]() |
#1 |
高级会员
注册日期: 2019-11-21
帖子: 3,006
声望力: 66 ![]() |
![]()
我有一个矩阵:
raw = [ 2001 1000 ; 2001 2000 ; 2001 1000 ; 2001 1000 ; 2001 2000 ; 5555 nan ; 5555 10000 ; 5555 20000 ; 5555 5000 ; 5555 20000 ; 5555 30000 ; 7777 1000 ; 7777 2000 ; 7777 3000 ; 7777 nan] ; 我需要根据Col1中的uniqIds查找Col2中每4个最后4行的总和(对于每个uniqId)。 Col2中也可能含有NaN。我想要的答案是: [2001 nan; 2001 nan; 2001 nan; 2001 5000; 2001 6000; 5555 nan; 5555 nan; 5555 nan; 5555 nan; 5555 55000; 5555 75000; 7777 nan 7777 nan 7777 nan ; 7777 nan] ; 原始矩阵仅具有> = 4行数据的元素。我不能使用for循环。如果可以的话,请以向量化形式帮助我。如果需要,我可以使用while循环。 回答: 您可以使用UNIQUE和ACCUMARRAY函数来执行此操作。以下假设每个组将至少包含4个元素。原始数据中存在的任何NaN值都将导致求和窗口的NaN值包括该值: [~,~,index] = unique(raw(:,1)); %# Get the indices for the unique values sumFcn = @(x) {sum(hankel([nan(3,1); x(1:numel(x)-3)],... %# Anonymous function x(numel(x)-3:end)),2)}; %# to get the sum %# over each window %# of four values sumPerID = accumarray(index,raw(:,2),[],sumFcn); %# Compute the windowed sum %# for each unique ID raw(:,2) = vertcat(sumPerID{:}) %# Place the results back into the second %# column of raw raw = 2001 NaN 2001 NaN 2001 NaN 2001 5000 2001 6000 5555 NaN 5555 NaN 5555 NaN 5555 NaN 5555 55000 5555 75000 7777 NaN 7777 NaN 7777 NaN 7777 NaN 更多&回答... |
![]() |
![]() |