MATLAB: Replace Specific Value in Specific part of the Main Matrix

replace specific valuesspecific part of matrix

Hello,
Suppose I have this Matrix
A=[0 1 2 2 2 0 1 0 2;0 1 1 1 1 1 1 1 0;2 1 2 1 1 2 1 2 0;0 0 1 0 1 1 1 0 2;0 2 0 1 0 2 0 1 2;0 0 1 2 2 2 2 0 2]
A =
0 1 2 2 2 0 1 0 2
0 1 1 1 1 1 1 1 0
2 1 2 1 1 2 1 2 0
0 0 1 0 1 1 1 0 2
0 2 0 1 0 2 0 1 2
0 0 1 2 2 2 2 0 2
I want to replace the value 1 to 0, only in one part of the matrix which is A(3:4,4:6), the other ones (1) and other values remain the same and unchanged. So The results I am expecting should be:
A =
0 1 2 2 2 0 1 0 2
0 1 1 1 1 1 1 1 0
2 1 2 0 0 2 1 2 0
0 0 1 0 0 0 1 0 2
0 2 0 1 0 2 0 1 2
0 0 1 2 2 2 2 0 2
How to do that?
I tried A(A(3:4,4:6)==1)=0, but It did Not give me the expected results, it gave me the following which changed the values of other elements, same thing happens when using find function.
A =
0 1 2 2 2 0 1 0 2
0 1 1 1 1 1 1 1 0
0 1 2 1 1 2 1 2 0
0 0 1 0 1 1 1 0 2
0 2 0 1 0 2 0 1 2
0 0 1 2 2 2 2 0 2
I also tried to divided the matrix into 9 parts, and change the part I want to be changed, then recombined these 9 parts (sub-matrices) to given the Main Matrix with required change, It worked! But is there a more efficient way to that,if yes I would be very glad, because dividing the matrix and recombine it, is kind of exhausting to do in my real problem.
Thanks in-advance Alaa

Best Answer

>> A = [0,1,2,2,2,0,1,0,2;0,1,1,1,1,1,1,1,0;2,1,2,1,1,2,1,2,0;0,0,1,0,1,1,1,0,2;0,2,0,1,0,2,0,1,2;0,0,1,2,2,2,2,0,2];
>> A(3:4,4:6) = A(3:4,4:6)-(A(3:4,4:6)==1)
A =
0 1 2 2 2 0 1 0 2
0 1 1 1 1 1 1 1 0
2 1 2 0 0 2 1 2 0
0 0 1 0 0 0 1 0 2
0 2 0 1 0 2 0 1 2
0 0 1 2 2 2 2 0 2
Related Question