一种方法 -
%// 3d mask of elements greater than 5
mask = m3d>5
%// Sum of all elements greater than 5 in each slice
sumvals = sum(reshape(m3d.*mask,[],size(m3d,3)))
%// Count of elements great than 5 in each slice
counts = sum(reshape(mask,[],size(m3d,3)))
%// Final output of mean values for the regions with >5 only
out = sumvals./counts
基准测试
这里有一些运行时测试,以了解所有发布的方法的位置。对于测试,我们采用了大小为1500 x 1500 x 100 的随机3D 数组,其值在[1,255] 区间内。接下来列出了基准测试代码 -
m3d = randi(255,1500,1500,100); %// Input 3D array
%// Warm up tic/toc.
for k = 1:50000
tic(); elapsed = toc();
end
disp('------------------------ With SUMMING and COUNTING ')
tic
%// .... Proposed approach in this solution
toc, clear out counts sumvals mask
disp('------------------------ With FOR-LOOP ')
tic
N = size(m3d, 3);
out = zeros(N, 1);
for k = 1:size(m3d,3)
val = m3d(:,:,k);
lix = val>5;
out(k) = mean(val(lix));
end;
toc, clear out lix val k N
disp('----------------------- With ACCUMARRAY')
tic
ind = m3d>5;
result = accumarray(ceil(find(ind)/size(m3d,1)/size(m3d,2)), m3d(ind), [], @mean);
toc, clear ind result
disp('----------------------- With NANMEAN')
tic
m3d(m3d<5) = NaN; %// Please note: This is a bad practice to change input
out = nanmean(nanmean(m3d,1),2);
toc
运行时
------------------------ With SUMMING and COUNTING
Elapsed time is 0.904139 seconds.
------------------------ With FOR-LOOP
Elapsed time is 2.321151 seconds.
----------------------- With ACCUMARRAY
Elapsed time is 4.350005 seconds.
----------------------- With NANMEAN
Elapsed time is 1.827613 seconds.