Effacer les filtres
Effacer les filtres

Efficient alternative to find()

9 vues (au cours des 30 derniers jours)
Chun Hei Chan
Chun Hei Chan le 13 Août 2023
Commenté : Star Strider le 13 Août 2023
I would like to see if there is any more efficient alternative to find() for this problem:
Let's say my x-values are x0= [1 ,1.1, 1.3, 1.5 ,1.6, 1.7] and the corresponding y-values are [ 2, 3 ,4 ,7, 9 ,11], i.e y is a "function" of x.
Suppose I have a new set of x-values given by x1 = [1.1, 1.12, 1.25, 1.55, 1.65,1.68].
I want to create a new vector y1 with y1(i) being equal to the value in the original y such that its corresponding x0(i) is the last element in x0 that is smaller than x1(i).
For this case, the vector y1 should be [3,3,3,7,9,9]. For example, y1(4) is equal to 7 because 1.5 is the last element in x0 that is smaller than 1.55.
I tried doing this with find() and loop over all vector entries but it turns out to be rather slow. Any advice on more efficient implementations would be appreciated.
Edit: My original example had a mistake

Réponse acceptée

Star Strider
Star Strider le 13 Août 2023
The interp1 function with the 'previous' interpolation method may be appropriate here —
x0= [1 ,1.1, 1.3, 1.5 ,1.6, 1.7];
y0 = [ 2, 3 ,4 ,7, 9 ,11];
x1 = [1.1, 1.12, 1.25, 1.55, 1.65,1.68];
y1 = interp1(x0, y0, x1, 'previous')
y1 = 1×6
3 3 3 7 9 9
.
  2 commentaires
Chun Hei Chan
Chun Hei Chan le 13 Août 2023
Thanks Strider, it worked perfectly.
Star Strider
Star Strider le 13 Août 2023
As always, my pleasure!

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Graphics Performance dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by