If you can use MATLAB, I would recommend you use the containers.Map
paradigm, which is essentially an associative array that performs key/value lookups. It also spits out errors if you throw in a value that is not part of the dictionary. As such, you simply provide an input/output relationship for each element in your mapping. The inputs are what are known as keys, and the outputs are what are known as values.
Once you're finished, you provide a cell array of input values into your dictionary / associate array with the values
function, then convert this cell array back into a numeric vector when you're finished. Judging from your input/output pairs, you want the inputs to be double
and the outputs to be double
as well. However, the problem with containers.Map
is that NaN
can't be used as a key. As such, a workaround would be to convert each element in your input numeric vector as a cell array of character keys, with the outputs defined as a cell array of character values.
We can achieve this with arrayfun
, which performs an operation over each value in an array. This is very much like a for
loop, but what's special is that if you specify the uni
flag to be 0
, the output of each corresponding element will be converted into a string. You then create your dictionary with these cell array of characters. Now, to do the mapping on your inputs, you'll have to convert these into a cell array of characters as well, then use values
to get what the corresponding outputs are, then use str2double
to convert each output cell element back and place it into a numeric array.
As such, borrowing from huntj's sample input, this is what you would have to do:
%// Input-Output relationships
in = [0,25,240,NaN];
out = [1,2,9,0];
%// Test inputs
vector = [0, 25, 240, NaN, 0, 25, 240, NaN];
% // For declaring our dictionary
in_cell = arrayfun(@num2str, in, 'uni', 0);
out_cell = arrayfun(@num2str, out, 'uni', 0);
% // Input test into dictionary
vector_cell = arrayfun(@num2str, vector, 'uni', 0);
% // Create dictionary
dict = containers.Map(in_cell, out_cell);
% // Put in inputs to be mapped
output_cell = values(dict,vector_cell);
% // Convert back to numeric array
output = str2double(output_cell);
This is what I get with the above code, with our final output stored in output
:
output =
1 2 9 0 1 2 9 0