I am trying to figure out how to encode integers based on given parameters. For example, I am given the table:
integer = 0, encoding is 3294
integer = 1, encoding is 128
integer = 2, encoding is 2098
etc.
How would I go about doing this? I have looked at the function dec2bin, but it's not exactly what I need. My input would be a vector, say x = [ 2 1 0 ]
and the output would be the vector y = [2 0 9 8 1 2 8 3 2 9 4]
.
Any advice or help is appreciated!
Encoding may not be the best word to describe this. This answer is just a direction in your search.
I would have a look at any dictionary
, hashtable
or map
data structures. Code below is based on solution described in this post
c = containers.Map;
c('0') = 3294;
c('1') = 128;
c('2') = 2098;
keys(c)
values(c)
You may need to add proper usings and maybe use integers types directly to remove casts and conversion overhead.
If you represent the encoding table as a cell array enc
with two columns (each row contains an integer and its corresponding encoding string), you can use the following neat one-liner:
y = str2num(cell2mat(arrayfun(@(v)enc{find([enc{:, 1}] == v), 2}', x(:), 'UniformOutput', 0)))'
Explanation
The above solution actually does three things:
Substitutes each integer in the input vector x
with the corresponding encoding string from enc
:
arrayfun(@(v)enc{find([enc{:, 1}] == v), 2}', x(:), 'UniformOutput', 0)
Concatenate all strings together into one column using cell2mat
.
Converts it back into a numerical vector using str2num
. str2num
is applied on rows, so each character (digit) is treated individually.
Example
enc = {0, '3294'; 1, '128'; 2, '2098'};
x = [2, 1, 0];
y = str2num(cell2mat(arrayfun(@(v)enc{find([enc{:, 1}] == v), 2}', x(:), 'UniformOutput', 0)))'
The result is:
y =
2 0 9 8 1 2 8 3 2 9 4