selectively replace elements in vector

I need to replace some of the values in a vector example
a = [ 2 2 2 2 3 3 3 3 7 7 4 4 4 4 4 7 7 7 7 7 7 1 1 1 ]
I need to replace only the 7's occurring between 3 and 4 , and put 3 or 4 there
thanks in advance.

4 comentarios

Walter Roberson
Walter Roberson el 23 de En. de 2013
If there was [3 7 1 5 9 4] then would the 7 be counted as being between 3 and 4 ?
You have as a sublist, [3 7 7 4]. Is either 7 counted as being between 3 and 4? The first 7 is between 3 and 7, and the second is between 7 and 4.
Which are you wanting to put in, 3 or 4 ?
Srinivas
Srinivas el 23 de En. de 2013
- the array that i am generating will always look similar to the one I gave in example,
- I am looking to replace both the 7's with 4
- another example of similar array will be [ 1 1 1 2 2 2 2 3 3 3 7 7 4 4 4 7 7 7 7 7 1 1 1 2 2 3 3 3 7 4 4 ]
here I am looking to replace the 7 in bold above.
thanks in advance.
Walter Roberson
Walter Roberson el 23 de En. de 2013
So if you have one or more 7's that is immediately preceded with a 3 and immediately followed by a 4, then the 7's are all to be changed to 4's ?
Srinivas
Srinivas el 23 de En. de 2013
only the 7's that are preceded by 3 and followed by 4 are to changed to 7 , other 7's to be left as it is .
Thanks

Iniciar sesión para comentar.

 Respuesta aceptada

Daniel Shub
Daniel Shub el 23 de En. de 2013
There are too many edge cases to give you a complete answer (and I don't want to do your work for you). Walter has tried to get at some of the edge cases, but your answer does not clarify the problem.
Given
a = [ 2 2 2 2 3 3 3 3 7 7 4 4 4 4 4 7 7 7 7 7 7 1 1 1 ]
you can find all the indices which are some value x with
find(a == x);
You probably need to to find all the indices that are 3, 4, and 7, and then look and see if there are any 7's between the 3's and 4's that meet your rules. You can create a set of nested loops that check each 3, 4, and 7 index. In the end you should create an array that has the indices of the 7's you want to replace
y = [9, 10];
You can then replace them with
a(y) = 4;
There are probably faster computational ways to solving the problem than nest for loops, but get the nested loops will potentially help you see the problems.

3 comentarios

Walter Roberson
Walter Roberson el 23 de En. de 2013
I don't think I would use nested loops: I would use the equivalent of a state machine. The array only has to be scanned once, in a forward direction.
Srinivas
Srinivas el 23 de En. de 2013
Thanks Daniel and Walter
Daniel Shub
Daniel Shub el 24 de En. de 2013
@Walter that is a nicer approach.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Matrices and Arrays en Centro de ayuda y File Exchange.

Preguntada:

el 23 de En. de 2013

Community Treasure Hunt

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

Start Hunting!

Translated by