Comparing two numerical arrays
조회 수: 3 (최근 30일)
이전 댓글 표시
I have two arrays of integer numbers. The first array can be thousands of entries long and contains numbers within a certain range. The second array denotes "sections" of the first array's entries. Let's say the first array contains numbers from 1 to 10. The second array could then e.g. contain the numbers 0, 3, 7, 10 (with both 0 and 10 (as the largest number of the first array) necessarily being there). I then want to create a third array with the same length as the first one, whose entries are determined as follows:
If the element of the first array is smaller than or equal to 3, but larger than 0, the corresponding element in the third array is 1. (In fact, every element in the first array is strictly larger than 0, so technically we could leave this out, but writing a loop becomes easier this way.) If it is smaller than or equal to 7, but larger than 3, the third array's value is 2. And if the first array's entry is smaller than or equal to 10, but larger than 7, the third array's entry is 3. So the second array implicitly shows the range of the sections, while the third array is supposed to show the actual index of the sections. This could be done quite easily with a loop, of course:
for i = 1:length(third_array)
for ii = 2:length(second_array)+1
if first_array(i) <= second_array(ii) && first_array(i) > second_array(ii-1)
third_array(i) = ii-1;
break;
end
end
end
But this seems rather inefficient to me. Is there a more efficient way to do this?
댓글 수: 0
채택된 답변
Bruno Luong
2022년 8월 26일
편집: Bruno Luong
2022년 8월 26일
Checkout discretize
secondarray=[0,3,7,10]
firstarray=randi([1 10],1,20)
thirdarray=discretize(firstarray,secondarray,'IncludedEdge','right')
추가 답변 (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!