如何使用逻辑索引MATLAB获取3d矩阵中每个切片中某些区域的平均值

How to get mean values of certain regions in each slice in 3d matrix using logical indexing MATLAB

在 Matlab 中,

如果我有一个如下所示的 3d 矩阵,我想知道每个切片中值大于 5 的区域的平均值。我怎样才能使用逻辑索引来做到这一点,请不要循环?

我想得到一个 3 x 1 的数组,每个元素表示相应切片中区域的平均值。

m3d = randi(10,[3,3,3])

m3d(:,:,1) =

 7     7     8
 1     9     8
 9     7     6

m3d(:,:,2) =

10    10     5
 9     7     8
 5     3     3

m3d(:,:,3) =

 9     7     5
 4     1     9
 5     9     1

获取索引

3d_index = m3d > 5;

我的决赛

result = mean(m3d(3d_index));

其中我不想得到所有区域的平均值

一种方法-

%// 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.

您可以使用掩码数组来执行此操作,如下所示,

m3d = randi(10,[3,3,3]);

%Set values less than 5 to NaN
m3d(m3d<5) = NaN
nanmean(nanmean(m3d,1),2)

这可以通过 accumarray 轻松完成:

ind = m3d>5;
result = accumarray(ceil(find(ind)/size(m3d,1)/size(m3d,2)), m3d(ind), [], @mean);