如何在MATLAB中使用2-D掩模索引3-D矩阵? [英] How can I index a 3-D matrix with a 2-D mask in MATLAB?
问题描述
假设我有D,一个X-by-Y-by-Z数据矩阵。我也有M,一个X-by-Y掩蔽矩阵。我的目标是当M中的(Xi,Yi)为假时将D中的元素(Xi,Yi,:)设置为NaN。
Suppose I have D, an X-by-Y-by-Z data matrix. I also have M, an X-by-Y "masking" matrix. My goal is to set the elements (Xi,Yi,:) in D to NaN when (Xi,Yi) in M is false.
有什么办法可以避免在循环中这样做?我尝试使用 ind2sub
,但失败了:
Is there any way to avoid doing this in a loop? I tried using ind2sub
, but that fails:
M = logical(round(rand(3,3))); % mask
D = randn(3,3,2); % data
% try getting x,y pairs of elements to be masked
[x,y] = ind2sub(size(M),find(M == 0));
D_masked = D;
D_masked(x,y,:) = NaN; % does not work!
% do it the old-fashioned way
D_masked = D;
for iX = 1:size(M,1)
for iY = 1:size(M,2)
if ~M(iX,iY), D_masked(iX,iY,:) = NaN; end
end
end
我怀疑我在这里遗漏了一些明显的东西。 (:
I suspect I'm missing something obvious here. (:
推荐答案
您可以通过复制逻辑掩码来实现此目的 M
使用 REPMAT 跨越第三维度,以便它是与 D
相同的大小。然后,索引离开:
You can do this by replicating your logical mask M
across the third dimension using REPMAT so that it is the same size as D
. Then, index away:
D_masked = D;
D_masked(repmat(~M,[1 1 size(D,3)])) = NaN;
如果不希望复制掩码矩阵,还有另一种选择。你可以先找到一组线性索引,其中 M
等于0,然后复制设置 size(D,3)
次,然后将每组索引移动 numel(M)
的倍数,这样它在第三维中为 D
的不同部分编制索引。我将在这里使用 BSXFUN :
If replicating the mask matrix is undesirable, there is another alternative. You can first find a set of linear indices for where M
equals 0, then replicate that set size(D,3)
times, then shift each set of indices by a multiple of numel(M)
so it indexes a different part of D
in the third dimension. I'll illustrate this here using BSXFUN:
D_masked = D;
index = bsxfun(@plus,find(~M),(0:(size(D,3)-1)).*numel(M));
D_masked(index) = NaN;
这篇关于如何在MATLAB中使用2-D掩模索引3-D矩阵?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!