How to manipulate arrays based on the transitions of the array elements?
3 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
James Kristoff
2013-5-7
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.
更多回答(1 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrices and Arrays 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!