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!