我需要重置3维矩阵的“下三角”。 这意味着,如果原始矩阵是:
C(:,:,1) = [1 2 3 ; 2 4 6 ; 3 6 9]
C(:,:,2) = [2 4 6 ; 4 8 12 ; 6 12 18]
C(:,:,3) = [3 6 9 ; 6 12 18 ; 9 18 27]
然后得到的矩阵应该是:
C(:,:,1) = [1 2 3 ; 2 4 6 ; 3 6 9]
C(:,:,2) = [0 0 0 ; 4 8 12 ; 6 12 18]
C(:,:,3) = [0 0 0 ; 0 0 0 ; 9 18 27]
知道如何做这样的事情吗? (我原来的3 dim矩阵很大)
谢谢!
答案 0 :(得分:6)
内置triu
无法处理此3D数组,但您可以在一个简单的循环中完成。
for k = 2:size(C, 3)
C(1:k-1,:,k) = 0;
end
答案 1 :(得分:4)
您可以使用permute
生成2D蒙版,bsxfun
尺寸,并乘以单张展开:
result = bsxfun(@times, C, permute((1:size(C,1)).'>=(1:size(C,2)), [1 3 2]));
或者,从版本R2016b起,您可以bsxfun
删除result = C .* permute((1:size(C,1)).'>=(1:size(C,2)), [1 3 2]);
:
{{1}}
答案 2 :(得分:1)
假设您有一个“正方形”3-D矩阵(即原始帖子3x3x3中的NxNxN),您还可以使用重塑和重新映射:
编辑:由于repmat太慢,我把它换成bsxfun实现。
[a,b,c] = size(C)
D = reshape(tril(ones(a)),[a,1,a]);
F = ones(1,size(E,1));
D = bsxfun(@times,D,F);
C(~D)=0;
我还对三种提议的解决方案进行了快速比较。 @ LuisMendo的解决方案对我不起作用,> =比较中存在矩阵维度误差(比较尺寸[1 N]和[N 1])。
在我和@Suever的解决方案之间,他的速度要快得多:
Comparing the three methods with variable size Cs:
Suever's version (for loop):
Took 0.3529s to compute.
Took 0.0002s to compute size 3x3x3.
Took 0.0008s to compute size 10x10x10.
Took 0.0008s to compute size 50x50x50.
Took 0.0455s to compute size 250x250x250.
Took 0.3055s to compute size 500x500x500.
My version (reshape/repmat):
Took 0.9086s to compute.
Took 0.0522s to compute size 3x3x3.
Took 0.0042s to compute size 10x10x10.
Took 0.0017s to compute size 50x50x50.
Took 0.1060s to compute size 250x250x250.
Took 0.7445s to compute size 500x500x500.