Linear Interpolation code without using interp1
18 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaire
Matt J
le 5 Oct 2023
What is the purpose of rewriting interp1? If it is a homework exercise, I don't think speed is supposed to matter.
Réponses (3)
Torsten
le 5 Oct 2023
Modifié(e) : Torsten
le 5 Oct 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 commentaires
Torsten
le 5 Oct 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.
Voir également
Catégories
En savoir plus sur Interpolation dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
