Linear Interpolation code without using interp1
16 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentar
Matt J
am 5 Okt. 2023
What is the purpose of rewriting interp1? If it is a homework exercise, I don't think speed is supposed to matter.
Antworten (3)
Torsten
am 5 Okt. 2023
Bearbeitet: Torsten
am 5 Okt. 2023
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 Kommentare
Torsten
am 5 Okt. 2023
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.
Siehe auch
Kategorien
Mehr zu Interpolation finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
