How to compare values in two arrays and find when the index of one array exceeds the index of another
조회 수: 2 (최근 30일)
이전 댓글 표시
I have two arrays of equal length that I am comparing. They are both in ascending order. I would like to compare the two array and find when array1 is greater than array2, then at that point make a third array that returns a '1' at that instance. once this has happened i would like array1 to take to value of the index where that instance is and array2 to continue searching from that instance until it finds the next value that is greater and so on. for example:
Array 1: [ 1 2 4 5 8 9 11]
Array 2: [1 2 3 4 5 6 7 ]
Array 3: [0 1 1 0 1 0 0 ]
index one of array1 is not less than index one of array2 so array 3 returns 0
index one of array1 is kept
index one of array one is less than index two of array2 so array3 returns 1
index two of array1 is now taken
index two of array1 is less than index three of array2 so array3 returns 1
index three of array1 is now taken
index three of array1 is not less than index four of array2 so array3 returns a 0
index three of array1 is kept
and so on....
so array1 keeps its value until the condition is met and then it takes the value of the index at which the condition is met and array2 continues one index at a time regardless looking for a value at which the array1 index is met.
댓글 수: 0
채택된 답변
Bob Thompson
2019년 2월 11일
i = 1;
j = 1;
k = 1;
while k <= size(A);
if A(i) >= B(j);
C(k) = 0;
k = k+1;
j = j+1;
else
C(k) = 1;
k = k+1;
j = j+1;
i = i+1;
end
end
I think this does what you want. If not, I may need you to try explaining it again.
댓글 수: 7
Bob Thompson
2019년 2월 11일
Is it indexing k correctly?
Unfortunately, I can't really see your screen shot at all, it's very small in the post. Without a full description of your array I would be unable to run sum1 and t1 correctly to get a similar total as you are.
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Matrix Indexing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
