What is the common way to "map" arbitrary values (of within a certain range) to discrete values of an array?
Basically what I'd like to do is precompute a complex function x = f(x)
for a range of discrete input values x
and store each output value f(x)
in another array fx
, so that there are two vectors:
x
- discrete input values andfx
- corresponding discrete output values
Now for an arbitrary value with the range of x
I'd like to get the corrsponding output from fx
, e. g. for a value x1 = 42
and vectors
x = [ 30, 35, 40, 45, 50];
fx = [1.3, 1.8, 2.9, 4.5, 7.3];
the function possibly could return
fx1 = 4.5
- mapping tofx
by takingx
as an upper boundfx1 = 2.9
- mapping tofx
taking the nearest value fromx
fx1 = 3.54
- mapping tofx
doing a simple linearization
fx1 = fxa + (fxb-fxa)/(xb-xa) * (x1-xa)
fx1 = 2.9 + (4.5-2.9)/(45-40) * (42-40)
The function* should be really fast, as it substitutes the calling of the "real" function in a tight loop. A first try which is used to put into practive the case one of the upper listing is the following:
%% GET AT
% Retrieve f(x).
%
% * Synopsis: getAt (x, input_map, output_map)
% * Input : x - function input
% : input_map - array with precomputed input values
% : output_map - array with precomputed output values
%
% * Output : fx - function output
%
function fx = getAt (x, input_map, output_map)
n = length(input_map);
jj = length(find(input_map < x));
if (jj >= n)
fx = 0;
else
fx = output_map(jj+1);
end
end
However I'm more looking for a C solution, because the loop also will be in C.
*.. Just looking for the way to do it not for a function as in language construct.