Linear Interpolation without interp1

10 views (last 30 days)
Bob Dylan
Bob Dylan on 25 Nov 2018
Edited: Rena Berman on 28 Nov 2018
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 Comments
John D'Errico
John D'Errico on 25 Nov 2018
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 on 28 Nov 2018

(Answers Dev) Restored edit

Sign in to comment.

Answers (1)

Stephen23
Stephen23 on 25 Nov 2018
Edited: Stephen23 on 25 Nov 2018
"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 Comments
Bob Dylan
Bob Dylan on 25 Nov 2018
e.g. 340 should produce values of ida=300 and idb=400. And I've no idea why it does not
Stephen23
Stephen23 on 25 Nov 2018
Edited: Stephen23 on 25 Nov 2018
"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)

Sign in to comment.

Categories

Find more on Multidimensional Arrays 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!