![]() |
在不使用MATLAB中的for循环的情况下计算列中某些行的总和(基于uniqId)
我有一个矩阵:
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循环。 [B]回答:[/B] 您可以使用[URL="http://www.mathworks.com/help/techdoc/ref/unique.html"]UNIQUE[/URL]和[URL="http://www.mathworks.com/help/techdoc/ref/accumarray.html"]ACCUMARRAY[/URL]函数来执行此操作。以下假设每个组将至少包含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 [url=https://stackoverflow.com/questions/4925724]更多&回答...[/url] |
所有时间均为北京时间。现在的时间是 04:49。 |
Powered by vBulletin
版权所有 ©2000 - 2025,Jelsoft Enterprises Ltd.