Replace Specific Value in Specific part of the Main Matrix

5 views (last 30 days)
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

Accepted Answer

Stephen23
Stephen23 on 28 Apr 2017
Edited: Stephen23 on 28 Apr 2017
>> 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
  1 Comment
Alaa Al-Saffar
Alaa Al-Saffar on 28 Apr 2017
Thank you Stephen
Very simple and lovely solution. Now I can code my problem more smoothly.
Thank you again.

Sign in to comment.

More Answers (1)

Guillaume
Guillaume on 28 Apr 2017
Another option is to save your matrix slice in a variable. Do whatever manipulation you need with that variable, then copy the modified slice back into the original matrix:
B = A(3:4, 4:6);
B(B == 1) = 0;
A(3:4, 4:6) = B;

Categories

Find more on Migrate GUIDE Apps in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!