If you are using a MATLAB version newer than 2008b, you can use the containers.Map class to do what you want, even with non-integer, non-consecutive or non-numeric values:
x = [ 1 2 3 4 5 6 7 8 9 10];
y = [ 3 6 2 4 1 6 7 0 1 8 ];
z = [ 2 3 8 9 10 3];
F = containers.Map(x,y);
% for a single element:
Fz1 = F(z(1))
% for multiple elements at the same time, you need to use arrayfun
Fz = arrayfun(@(x)(F(x)),z)
The Map class actually creates a so-called hashmap, so you can map almost any value to other values (e.g. strings, cells, array, ...).
When the item is not present, it will return an error.
If you cannot use MATLAB 2008b or newer, there are three possibilities for non-integer domain values.
Use an interpolation method such as interp1
. That might give false values (at values that weren't provided beforehand). You can check for that case by using ismember(z, x)
.
Secondly, you could invent your own scheme from non-integers to integers (e.g. if all your values are multiples of 0.5, multiply by 2) and use the solution Oli has shown.
The other solution is to use struct
s to mimic the behavior of a map. Then you only need a conversion from your domain values to valid field names (i.e. strings that are valid variable names in MATLAB, that may be possible by using the genvarname
function).
These last two solutions are somewhat dirty and prone to errors if you don't take rounding into consideration. So I see them only as a last resort.