Comparing two numerical arrays
3 views (last 30 days)
Show older comments
Dominik Rhiem
on 26 Aug 2022
Commented: Dominik Rhiem
on 26 Aug 2022
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 Comments
Accepted Answer
Bruno Luong
on 26 Aug 2022
Edited: Bruno Luong
on 26 Aug 2022
Checkout discretize
secondarray=[0,3,7,10]
firstarray=randi([1 10],1,20)
thirdarray=discretize(firstarray,secondarray,'IncludedEdge','right')
More Answers (0)
See Also
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!