To change value in cells based on conditions
Mostrar comentarios más antiguos
I have coding as below.
a=[11 11 33 33 22 44; 33 33 33 11 11 22; 33 33 11 22 22 44; 44 44 33 22 44 11]
I need to change the matrix value based on this conditions and cannot overlap each other:
1. if value 33 occured 3 times continuosly, the end of 33 need to replace with 44
33 33 33 = 33 33 44
2. If value 33 appeared 2 times continously and followed by 22, I need to replace the 22 value with 44 too.
33 33 22 = 33 33 44
2. if value 33 occured then followed by value 11, the value 11 will change into 22
33 11 = 33 22
Therefore, origin matrix will become like this:
c=
11 11 33 33 44 44
33 33 44 11 11 22
33 33 44 22 22 44
44 44 33 22 44 11
I need help to code this problem. Thank you for your help.
Respuesta aceptada
Más respuestas (3)
Walter Roberson
el 5 de En. de 2012
0 votos
Use logical vectors for the various conditions. If you think about logical vectors a bit you will come up with a simple way to prevent overlaps between the conditions.
Question:
What should be the output for 33 33 33 33 11
2 comentarios
yue ishida
el 5 de En. de 2012
Walter Roberson
el 5 de En. de 2012
Okay... it just wasn't clear whether your mention of three 33's was exactly three or was "three or more".
yair suari
el 5 de En. de 2012
0 votos
something like (not very efficient)
for i=1:size(a,1) if a(i:i+2)==[33 33 33];a(i:i+2)=[33 33 44] end
1 comentario
Jan
el 5 de En. de 2012
Or: "a(i+2) = 44" - there is no need to overwrite 33 by 33.
yue ishida
el 5 de En. de 2012
2 comentarios
Jan
el 5 de En. de 2012
if all(a(i:i+2)==[33 33 33]) % better an explicite ALL
a(i+2)=44; % No need to overwrite the 33 with 33
...
yue ishida
el 6 de En. de 2012
Categorías
Más información sobre Matrix Indexing en Centro de ayuda y File Exchange.
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!