2

我有一个由 3 个矩阵 500x500 元素组成的 3D 矩阵。现在,我想取第三个矩阵并用 0 替换它的所有值,比方说,大于 100。如果我有一个矩阵 a,我的代码就是:

a(a>100)=0

但是,就我而言,我需要采用 3D 矩阵的第三个矩阵,即 a(:,:,3)。如果我现在尝试使用相同的代码:

a(:,:,3)(a(:,:,3)>100)=0

我收到消息“()-索引必须出现在索引表达式的最后。”

关于我如何表达的任何想法?

4

3 回答 3

4

关于什么

 a(:,:,3) = (a(:,:,3)<100).*a(:,:,3);

?

于 2012-11-23T15:15:10.357 回答
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 的原始代码,但适用于 2D 矩阵而不是 3D :)

于 2012-11-23T15:18:28.987 回答
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

似乎赢家是angaior :)

于 2012-11-23T15:32:27.240 回答