Matlab 将二维阈值应用于三维阵列

Matlab 将二维阈值应用于三维阵列,matlab,multidimensional-array,threshold,temperature,Matlab,Multidimensional Array,Threshold,Temperature,对于尺寸为20x30的地理网格,我有两个(温度)变量: 数据A大小为20x30x100 和一个阈值大小为20x30 我想对数据应用阈值,即在A中去掉高于threshold的值,每个网格点都有自己的阈值。因为这将为每个网格点提供不同数量的值,所以我想用零填充其余部分,这样得到的变量,我们称之为B,大小也将为20x30x100 我本来想做这样的事情,但是循环有点问题: B = sort(A,3); %// sort third dimension in ascending order thresho

对于尺寸为20x30的地理网格,我有两个(温度)变量:

数据
A
大小为20x30x100
和一个
阈值
大小为20x30

我想对数据应用阈值,即在
A
中去掉高于
threshold
的值,每个网格点都有自己的阈值。因为这将为每个网格点提供不同数量的值,所以我想用零填充其余部分,这样得到的变量,我们称之为
B
,大小也将为20x30x100

我本来想做这样的事情,但是循环有点问题:

B = sort(A,3); %// sort third dimension in ascending order
threshold_3d = repmat(threshold,1,1,100); %// make threshold into same size as B

for i=1:20
    for j=1:30
        if B(i,j,:) > threshold_3d(i,j,:); %// if B is above threshold
          B(i,j,:); %// keep values
        else
          B(i,j,:) = 0; %// otherwise set to zero
        end
    end
end
循环的正确方法是什么?
还有什么其他的选择呢

谢谢你的帮助

您可以使用更高效的解决方案,该解决方案将在内部处理使用
repmat
进行的复制,如下所示-

B = bsxfun(@times,B,bsxfun(@gt,B,threshold))
B(bsxfun(@le,B,threshold)) = 0
更有效的解决方案可能是将
bsxfun(gt
)创建的掩码中的
False
元素设置为零,即使用
bsxfun(
B
中的@le
)的
True
元素设置为零,从而避免使用
bsxfun(@times
,这对于大型多维数组来说可能有点昂贵,就像这样-

B = bsxfun(@times,B,bsxfun(@gt,B,threshold))
B(bsxfun(@le,B,threshold)) = 0
效率注意事项:
作为一种关系操作,使用
bsxfun
进行矢量化操作将提供内存和运行时效率。内存效率部分已在此处讨论,性能数字已在此处研究

样本运行-

 >> B
 B(:,:,1) =
      8     3     9
      2     8     3
 B(:,:,2) =
      4     1     8
      4     5     6
 B(:,:,3) =
      4     8     5
      5     6     5
 >> threshold
 threshold =
      1     3     9
      1     9     1
 >> B(bsxfun(@le,B,threshold)) = 0
 B(:,:,1) =
      8     0     0
      2     0     3
 B(:,:,2) =
      4     0     0
      4     0     6
 B(:,:,3) =
      4     8     0
      5     0     5