KiMaN
KiMaN

Reputation: 319

Matlab replacing specific values with condition in matrix

I have a mistake with matrices. I don't understand why it isn't working. Here is the code:

A = zeros(3,3,3);
A(:,:,1) = [1 2 3; 4 5 6; 7 8 9];
A(:,:,2) = [1 2 3; 1 2 3; 1 2 3];
A(:,:,3) = [1 2 3; 4 5 6; 7 8 9];

I want to replace only values that respect a condition in the 2nd dimension only, using this :

A(A(:,:,2)==1)=0

but it replaces the 1st dimension ! :

0     2     3
0     5     6
0     8     9

Is there anyone who can explain to me why that does not work, please?

Upvotes: 0

Views: 117

Answers (1)

ibezito
ibezito

Reputation: 5822

The problem with this line is that your are applying a 2D mask (A(:,:,2)==1) on A, which has 3 dimensions.

Instead, you can use the following approach:

temp = A(:,:,2);
temp(temp==1)=0;
A(:,:,2) = temp;

Upvotes: 1

Related Questions