【问题标题】:Apply 2D threshold to 3D array将 2D 阈值应用于 3D 阵列
【发布时间】:2015-12-15 16:21:17
【问题描述】:

使用大小为 20x30 的地理网格,我有两个(温度)变量:

数据A,大小为20x30x100
和一个 threshold 大小为 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

执行循环的正确方法是什么?
还有什么其他选择可以做到这一点?

感谢您的帮助!

【问题讨论】:

    标签: matlab multidimensional-array threshold temperature


    【解决方案1】:

    您可以使用bsxfun 获得更有效的解决方案,该解决方案将在内部处理使用repmat 完成的复制,就像这样 -

    B = bsxfun(@times,B,bsxfun(@gt,B,threshold))
    

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

    B(bsxfun(@le,B,threshold)) = 0
    

    Note on efficiency : 作为一个关系运算,使用bsxfun 的矢量化运算将提供内存和运行时效率。内存效率部分已在此处讨论 - BSXFUN on memory efficiency with relational operations,性能数据已在此处研究 - Comparing BSXFUN and REPMAT

    示例运行 -

     >> 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
    

    【讨论】:

      猜你喜欢
      • 2015-05-23
      • 2018-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多