A way to speed up my custom interpolation algorithm?
Ältere Kommentare anzeigen
I'm writing a simulation program which often has to read out data from small data tables.
The x and y values are provided as 1xn arrays:
x = [0, 2, 5, 9, 14, 67];
y = [0, 3, 8, 2, 45, 324];
The interpolation scheme i need is equivalent to
interp1(x,y,4,'previous','extrap');
But as interp1 is very slow i wrote my own function. According to Matlab Profiler it is 5x faster but still takes up 80% of my code runtime.
function y = table_lookup(x,table_y,table_x)
% Check if lookup tables are of the same length
assert(length(table_y) == length(table_x))
% initialize y
y = NaN;
% Iterate over lookup table
i = 1;
while i <= length(table_x)
% If x value is exactly in the x_table assign corresponding y value
if table_x(i) == x
y = table_y(i);
break;
% If x value is grater than x value assign previous y value
elseif table_x(i) > x && i ~= 1
y = table_y(i-1);
break;
end
i = i + 1;
end
% If the iteration completed over the whole table assign the last y value
if i > length(table_x)
y = table_y(end);
end
end
Maybe someone has a suggestion for possible optimizations?
Akzeptierte Antwort
Weitere Antworten (1)
Jon
am 8 Mai 2023
0 Stimmen
You could try benchmarking this way too for comparison
xe = [x inf]
yq = y(xq >= xe(1:end-1) & xq <xe(2:end))
This returns empty if xq is less than the first element in x, not sure if you need to handle this edge case.
Kategorien
Mehr zu Logical finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!