Borrar filtros
Borrar filtros

How to manipulate arrays based on the transitions of the array elements?

1 visualización (últimos 30 días)
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?

Respuesta aceptada

James Kristoff
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)

Micky
Micky el 8 de Mayo de 2013
Thanks James for the answer. I appreciate it!
Just for FYI. I also figured out another way i.e. Rotate the aa one time to the left and one time to the right by 1 and get the new array by multiplying the rotated arrays and finally replace the 0's by 1's.

Categorías

Más información sobre Matrix Indexing 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!

Translated by