Efficient alternative to find()

조회 수: 4 (최근 30일)
Chun Hei Chan
Chun Hei Chan 2023년 8월 13일
댓글: Star Strider 2023년 8월 13일
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

채택된 답변

Star Strider
Star Strider 2023년 8월 13일
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
Chun Hei Chan
Chun Hei Chan 2023년 8월 13일
Thanks Strider, it worked perfectly.
Star Strider
Star Strider 2023년 8월 13일
As always, my pleasure!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by