Linear Interpolation code without using interp1
23 次查看(过去 30 天)
显示 更早的评论
I need to write a code that does linear interpolation. (without using interp1) My function has 3 inputs (n,x,n2). Vector n contains the sample points, and x contains the corresponding values, x(n). Vector n2 contains the coordinates of the query points. My code is this:
function ynew = interpolate(n,x,n2)
for i = 1:length(n2)
for j = 1:length(n)-1
if n2(i) >= n(j) & n2(i) <= n(j+1)
ynew(i) = x(j) + (x(j+1)-x(j))/(n(j+1)-n(j)) * (n2(i)-n(j));
end
end
end
end
The problem is that it is much slower than interp1(n,x,n2,'linear'). How can I write a code that works faster?
1 个评论
Matt J
2023-10-5
What is the purpose of rewriting interp1? If it is a homework exercise, I don't think speed is supposed to matter.
回答(3 个)
Torsten
2023-10-5
编辑:Torsten
2023-10-5
How can I write a code that works faster?
Allocate ynew = zeros(size(n2)) at the beginning of your code.
Check whether n is monotonically ordered.
Check whether min(n) <= n2 <= max(n).
After you have implemented these three points and you want to speed up your code, edit and understand interp1.
(Means: you shouldn't expect your code to be as fast as a professional code. What you've done on your own is not that bad).
2 个评论
Torsten
2023-10-5
Most probably, interp1.m is only a driver function for the user. The real algorithmic implementation of the interpolation algorithm is hidden in this internal function.
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
