How to manipulate arrays based on the transitions of the array elements?
3 views (last 30 days)
Show older comments
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 Comments
Accepted Answer
James Kristoff
on 7 May 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.
More Answers (1)
See Also
Categories
Find more on Matrices and Arrays in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!