How to manipulate arrays based on the transitions of the array elements?
3 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
I want o make every element of the existing array to 1, but whenever there is a transition like the element value changes from -1 to 1 or 1 to -1, I want to keep those elements as -1 -1, it will be more clear from example below:
If I have a array like this:
aa = [0 0 0 -1 -1 -1 -1 1 1 1 1 -1 -1 -1 -1 ]
and I want to manipulate it in such a way to get a new array like
bb = [1 1 1 1 1 1 -1 -1 1 1 -1 -1 1 1 1].
How should I do that?
0 comentarios
Respuesta aceptada
James Kristoff
el 7 de Mayo de 2013
One way to do this is with a combination of logical indexing some knowledge of the problem. For instance we know that the transitions you want to mark with a -1 are located any time the difference of consecutive numbers is either 2 (1 - -1), or -2 (-1 - 1). Using that information I wrote the following code:
aa = [0 0 0 -1 -1 -1 -1 1 1 1 1 -1 -1 -1 -1 ];
bb = ones(size(aa));
bb(([abs(diff(aa)), 0] > 1 | [0, abs(diff(aa))] > 1)) = -1;
This code initiallizes a vector bb to be all ones, the same size as aa, then it uses a combination of the abs and diff functions to create a vector of logical (true or false) values that is true in the location that starts the transition and in the following location.
indx = ([abs(diff(aa)), 0] > 1 | [0, abs(diff(aa))] > 1);
Then it uses this logical to selectively modify bb, by assigning the value -1 to those locations.
Más respuestas (1)
Ver también
Categorías
Más información sobre Matrices and Arrays en Help Center y File Exchange.
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!