Replace Specific Value in Specific part of the Main Matrix

5 次查看(过去 30 天)
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

采纳的回答

Stephen23
Stephen23 2017-4-28
编辑:Stephen23 2017-4-28
>> 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 个评论
Alaa Al-Saffar
Alaa Al-Saffar 2017-4-28
Thank you Stephen
Very simple and lovely solution. Now I can code my problem more smoothly.
Thank you again.

请先登录,再进行评论。

更多回答(1 个)

Guillaume
Guillaume 2017-4-28
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;

类别

Help CenterFile Exchange 中查找有关 Migrate GUIDE Apps 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by