Comparing two numerical arrays

3 ビュー (過去 30 日間)
Dominik Rhiem
Dominik Rhiem 2022 年 8 月 26 日
コメント済み: Dominik Rhiem 2022 年 8 月 26 日
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?

採用された回答

Bruno Luong
Bruno Luong 2022 年 8 月 26 日
編集済み: Bruno Luong 2022 年 8 月 26 日
Checkout discretize
secondarray=[0,3,7,10]
secondarray = 1×4
0 3 7 10
firstarray=randi([1 10],1,20)
firstarray = 1×20
3 10 2 9 3 3 2 10 3 6 2 3 7 7 8 3 5 1 7 3
thirdarray=discretize(firstarray,secondarray,'IncludedEdge','right')
thirdarray = 1×20
1 3 1 3 1 1 1 3 1 2 1 1 2 2 3 1 2 1 2 1
  1 件のコメント
Dominik Rhiem
Dominik Rhiem 2022 年 8 月 26 日
Awesome, thanks!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

タグ

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by