在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
为interval的随机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.
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句