简体   繁体   中英

Replacing elements of a 3D matrix in MATLAB

I have a 3D matrix that consists of 3 matrices 500x500 elements. Now, I wanna take the third matrix and replace all its values that are, let's say, bigger than 100 with 0. If I have a matrix a, my code would simply be:

a(a>100)=0

However, in my case I need to take the third matrix of my 3D matrix, which would be a(:,:,3). If I now try to use the same code:

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

I get the message "()-indexing must appear last in an index expression."

Any idea on how I can express that?

What about

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

?

You can use linear indexes for that:

id = find(A(:,:,3)>100)+2*size(A, 1)*size(A, 2);
A(id)=0

Alternatively, you can reshape array A to 2D and:

AA = reshape(A, 500*500, 3);
AA(AA(:,3)>100,3) = 0;
A = reshape(AA, 500, 500,3);

which uses the original code of Acorbe, but works for 2D matrices in contrast to 3D :)

Just to add another alternative:

A(cat(3, false(size(A,1),size(A,2),2), A(:,:,3)>100)) = 0;

Alternatively, you can assign an index variable in 3D like so:

id(:,:,3) = A(:,:,3)>100;
A(id) = 0;

which has a much more cleaner syntax.

Now for some speed tests:

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

Results:

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

Seems the winner is angainor :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM