簡體   English   中英

Matlab中沿nd數組維度的平均bin

[英]average bins along a dimension of a nd array in matlab

例如,要計算沿Matlab中nd數組維度的每個bin的平均值,請沿4d數組的dim 4平均每10個元素的平均值

x = reshape(1:30*30*20*300,30,30,20,300);    
n = 10; 
m = size(x,4)/10;
y = nan(30,30,20,m);
for ii = 1 : m
    y(:,:,:,ii) = mean(x(:,:,:,(1:n)+(ii-1)*n),4);
end

看起來有點傻。 我認為必須有更好的方法來平均垃圾箱?

此外,是否可以使腳本適用於一般情況,即數組的arndray ndims以及沿arbitray變暗以求平均的情況?

對於問題的第二部分,可以使用以下命令:

x = reshape(1:30*30*20*300,30,30,20,300);    
dim = 4;
n = 10; 
m = size(x,dim)/10;
y = nan(30,30,20,m);
idx1 = repmat({':'},1,ndims(x));
idx2 = repmat({':'},1,ndims(x));
for ii = 1 : m
    idx1{dim} = ii;
    idx2{dim} = (1:n)+(ii-1)*n;
    y(idx1{:}) = mean(x(idx2{:}),dim);
end

對於問題的第一部分,這里是使用cumsumdiff的替代方法,但它可能比循環解決方案更好:

function y = slicedmean(x,slice_size,dim)
    s = cumsum(x,dim);
    idx1 = repmat({':'},1,ndims(x));
    idx2 = repmat({':'},1,ndims(x));
    idx1{dim} = slice_size;
    idx2{dim} = slice_size:slice_size:size(x,dim);
    y = cat(dim,s(idx1{:}),diff(s(idx2{:}),[],dim))/slice_size;
end

這是使用accumarray函數的通用解決方案。 我還沒有測試它的速度。 雖然可能還有一些改進的空間。

基本上,accumarray根據您的問題的自定義索引矩陣將x中的值分組

x = reshape(1:30*30*20*300,30,30,20,300); 
s = size(x);

% parameters for averaging
dimAv = 4; 
n = 10;

% get linear index
ix = (1:numel(x))';

% transform them to a matrix of index per dimension
% this is a customized version of ind2sub
pcum = [1 cumprod(s(1:end-1))];
sub = zeros(numel(ix),numel(s));
for i = numel(s):-1:1,
    ixtmp = rem(ix-1, pcum(i)) + 1;
    sub(:,i) = (ix - ixtmp)/pcum(i) + 1;
    ix = ixtmp;
end

% correct index for the given dimension
sub(:,dimAv) = floor((sub(:,dimAv)-1)/n)+1;

% run the accumarray to compute the average
sout = s;
sout(dimAv) = ceil(sout(dimAv)/n);
y = accumarray(sub,x(:), sout, @mean);

如果您需要更快的內存效率操作,則必須編寫自己的mex函數。 我想這應該沒那么困難!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM