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!