有效地将数据拆分为 bin

use*_*193 5 performance matlab

我想将我的data变量拆分为不同的变量a bc,并应用于mean垃圾箱(第一维)。有没有办法在速度方面显着(例如 1 倍数量级)改进此代码?欢迎一般反馈

data=rand(20,1000); %generate data
bins=[5 10 5]; %given size of bins
start_bins=cumsum([1 bins(1:end-1)]);
end_bins=cumsum([bins]);
%split the data into 3 cell arrays and apply mean in 1st dimension
binned_data=cellfun(@(x,y) mean(data(x:y,:),1),num2cell(start_bins),num2cell(end_bins),'uni',0);
%data (explicitly) has be stored into different variables
[a,b,c]=deal(binned_data{:});
whos a b c
  Name      Size              Bytes  Class     Attributes

  a         1x1000             8000  double              
  b         1x1000             8000  double              
  c         1x1000             8000  double              
Run Code Online (Sandbox Code Playgroud)

Wol*_*fie 3

你可以使用splitapplyaccumarray稍微友好一点的小兄弟):

% Your example
data = rand(20,1000); % generate data
bins = [5 10 5];      % given size of bins

% Calculation
bins = repelem(1:numel(bins), bins).'; % Bin sizes to group labels
binned_data = splitapply( @mean, data, bins ); % splitapply for calculation
Run Code Online (Sandbox Code Playgroud)

的行binned_data是您的a,bc

  • 我不知道“splittapply”可以与数据矩阵一起按行(或按列)工作。好发现! (2认同)
  • @Luis只要分组向量(相应的行或列)与大小匹配,它就像您喜欢的隐式扩展一样工作! (2认同)