Effacer les filtres
Effacer les filtres

Replace Specific Value in Specific part of the Main Matrix

8 vues (au cours des 30 derniers jours)
Alaa Al-Saffar
Alaa Al-Saffar le 28 Avr 2017
Commenté : Alaa Al-Saffar le 28 Avr 2017
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

Réponse acceptée

Stephen23
Stephen23 le 28 Avr 2017
Modifié(e) : Stephen23 le 28 Avr 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 commentaire
Alaa Al-Saffar
Alaa Al-Saffar le 28 Avr 2017
Thank you Stephen
Very simple and lovely solution. Now I can code my problem more smoothly.
Thank you again.

Connectez-vous pour commenter.

Plus de réponses (1)

Guillaume
Guillaume le 28 Avr 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;
  1 commentaire
Alaa Al-Saffar
Alaa Al-Saffar le 28 Avr 2017
Thank you Guillaume
This is also another simple and lovely solution.
Many thanks

Connectez-vous pour commenter.

Catégories

En savoir plus sur Migrate GUIDE Apps dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by