How do I resolve these two lines separately?
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
Sandi Homolak
el 21 de Abr. de 2022
Comentada: Jon
el 21 de Abr. de 2022
So I have matrix A that is 3x5 and a matrix B with random values and same dimensions as matrix A.
I want to find the elements in matrix B where the generated random number is lower than 0.6 and then change the coresponding elements in matrix A from 0 to 1 or from 1 to 0. Is there a way to do this without going into a for loop?
B=rand(3,5)
A=[0 0 0 1 0;1 1 1 0 0;1 0 1 1 0]
A(B<0.6 & A==0)=1
A(B<0.6 & A==1)=0
When I run this code it does what it's supposed to but the last line takes the newly-formed ones and then turnes them into zeros as well (which is not what i want).
2 comentarios
Jon
el 21 de Abr. de 2022
Can you please clarify what you are trying to do. What is the role of the original values of A in this. Maybe give a small example.
Respuesta aceptada
Más respuestas (3)
Les Beckham
el 21 de Abr. de 2022
Another approach
B=rand(3,5)
A=[0 0 0 1 0;1 1 1 0 0;1 0 1 1 0]
idx = B > 0.6
A(idx) = ~A(idx)
0 comentarios
Jon
el 21 de Abr. de 2022
Editada: Jon
el 21 de Abr. de 2022
It looks like you may have already answered your own question, but I think this is a little cleaner approach to do the same thing
B=rand(3,5)
A=[0 0 0 1 0;1 1 1 0 0;1 0 1 1 0]
Aold = A;
A(B<0.6 & Aold==1) = 0;
A(B<0.6 & Aold==0) = 1;
1 comentario
Jon
el 21 de Abr. de 2022
Actually you can do it in one line
A = double((B < 0.6 & ~A) | (B > 0.6 & A))
I turn the result into a double otherwise you would have a logical array rather than an array of ones and zeros. Not sure if that matters for your application
Ver también
Categorías
Más información sobre Solver Outputs and Iterative Display en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!