Linear Interpolation without interp1

조회 수: 6 (최근 30일)
Bob Dylan
Bob Dylan 2018년 11월 25일
편집: Rena Berman 2018년 11월 28일
So I have a range of data values (in asending orders of x) for x and y coordinates. I ask the user to enter an x value between the range of values. My code should basically caculate the linear gradient from the nearest data points at either side of the entered value. This is part of a big script but this part is causing difficulties. I thought there would be some way to identify the previous/next element from the entered x value in the array but I can''t manage to do this. Any help would be greatly appreciated.
  댓글 수: 6
John D'Errico
John D'Errico 2018년 11월 25일
Then you need to do some thinking. After all, it is your homework. Surely you can just use a loop going through the data. If you want, sort them first. And, if you are not allowed to use sort, or max, or tools like that, nothing stops you from writing the necessary tools. If x is sorted already, then it is a simple search to find the largest value in x that does not exceed the point in question. It is still easy even if not sorted. I might even guess that along the way, you may have had to write a sorting tool at some point.
So, yes, there are lots of ways to do this, but you yourself admit that you cannot use the functions that would make your problem easy.
Rena Berman
Rena Berman 2018년 11월 28일

(Answers Dev) Restored edit

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

답변 (1개)

Stephen23
Stephen23 2018년 11월 25일
편집: Stephen23 2018년 11월 25일
"I thought there would be some way to identify the previous/next element from the entered x value in the array but I can't manage to do this"
Of course this is easy with some logical comparisons:
>> Xv = 1:5
Xv =
1 2 3 4 5
>> Xq = 2.5;
>> ida = find(Xv<Xq,1,'last')
ida = 2
>> idb = find(Xv>Xq,1,'first')
idb = 3
Of course you will also need to hande some special cases, e.g. when Xq is equal to one of the values in Xv, or e.g. Xq is outside the range of values in Xv.
  댓글 수: 7
Bob Dylan
Bob Dylan 2018년 11월 25일
e.g. 340 should produce values of ida=300 and idb=400. And I've no idea why it does not
Stephen23
Stephen23 2018년 11월 25일
편집: Stephen23 2018년 11월 25일
"e.g. 340 should produce values of ida=300 and idb=400. And I've no idea why it does not"
Not it should not. If you had read the find documentation you would know that for its first output argument find returns indices of the non-zero elements, not values of the elements. Reading the find documentation is a good way to know what find actually does.
Using those indices is easy:
t(ida)
t(idb)

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

카테고리

Help CenterFile Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by