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
ormap
data structures. Code below is based on solution described in this postYou 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:Explanation
The above solution actually does three things:
Substitutes each integer in the input vector
x
with the corresponding encoding string fromenc
: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
The result is: