我有一个3D矩阵,由3个矩阵500x500元素组成。现在,我想取第三个矩阵并用0代替它所有的值,比如大于100。如果我有一个矩阵a,我的代码就是:
a(a>100)=0
然而,在我的情况下,我需要采用我的3D矩阵的第三个矩阵,它将是(:,:,3)。 如果我现在尝试使用相同的代码:
a(:,:,3)(a(:,:,3)>100)=0
我收到消息“() - 索引必须出现在索引表达式的最后。”
关于我如何表达的任何想法?
答案 0 :(得分:4)
怎么样?
a(:,:,3) = (a(:,:,3)<100).*a(:,:,3);
答案 1 :(得分:3)
您可以使用线性索引:
id = find(A(:,:,3)>100)+2*size(A, 1)*size(A, 2);
A(id)=0
或者,您可以reshape
数组A
到2D和:
AA = reshape(A, 500*500, 3);
AA(AA(:,3)>100,3) = 0;
A = reshape(AA, 500, 500,3);
使用Acorbe的原始代码,但与3D形成对比的2D矩阵:)
答案 2 :(得分:3)
只是添加另一种选择:
A(cat(3, false(size(A,1),size(A,2),2), A(:,:,3)>100)) = 0;
或者,您可以像这样分配3D的索引变量:
id(:,:,3) = A(:,:,3)>100;
A(id) = 0;
具有更清晰的语法。
现在进行一些速度测试:
clc, clear all
b = 250*rand(500,500, 3);
% Me 1
tic
for ii = 1:1e2
A=b;
clear id
id = cat(3, false(size(A,1),size(A,2),2), A(:,:,3)>100);
A(id) = 0;
end
toc
% Acorbe
tic
for ii = 1:1e2
A=b;
A(:,:,3) = (A(:,:,3)<100).*A(:,:,3);
end
toc
% angainor 1
tic
for ii = 1:1e2
A=b;
clear id
id = find(A(:,:,3)>100) + 2*size(A, 1)*size(A, 2);
A(id)=0;
end
toc
% Me 2
tic
for ii = 1:1e2
A=b;
clear id
id(:,:,3) = A(:,:,3)>100;
A(id) = 0;
end
toc
% angainor 2
tic
for ii = 1:1e2
A=b;
clear id
AA = reshape(A, [], 3);
AA(AA(:,3)>100,3) = 0;
A = reshape(AA, size(A,1), size(A,2), 3);
end
toc
结果:
Elapsed time is 1.612787 seconds. % me #1
Elapsed time is 1.223496 seconds. % Acorbe
Elapsed time is 1.606858 seconds. % angainor #1
Elapsed time is 1.510153 seconds. % me #2
Elapsed time is 0.964423 seconds. % angainor #2
似乎胜利者是angainor :)