Home > Blockchain >  Converting a string of chars to an array of numbers according to a dictionary in matlab
Converting a string of chars to an array of numbers according to a dictionary in matlab

Time:09-23

I have a string containing letters. I want to assing a number to each letter, and convert it to an array. Let's say I have

'ABAABCCBA'

and I have a dictionary such that A=1, B=2, C=3 and thus the array I want is

[1,2,1,1,2,3,3,2,1]

This is super easy to do in python, but I have to use matlab for some subsequent analysis. Any ideas as to how I can do this without switch case, as succinctly as possible? (Note that this is an MRE and the original string contains 20 different letters)

CodePudding user response:

A general method, which doesn't assume that keys or values are consecutive, is as follows:

keys = 'ABC';
values = [1 200 30];
data = 'ABAABCCBA';
[~, result] = ismember(data, keys);
result = values(result);
  • Related