Unless performance is a real concern here, I wouldn't bother with a lookup table. There's a simple way to convert your characters into numbers.
Take each of your strings, upper case them using upper
, subtract off 'A' and add one to convert all 'A's into '1's, 'B's into '2's, etc.
s = 'Bob';
num_s = upper(s) - 'A' + 1;
I am still curious maybe for my own development to learn how to examine a character, match it to an entry in another vector and recall a value it corresponds to. – user1499689
To do this is easy in Matlab. Let's say you have a lookup table of 26 elements, lookup
lookup = zeros(26,1);
% define the lookup table
for i=1:numel(lookup)
lookup(i) = 2*i - 7; % some random function
end
Now, using the char-to-number conversion above:
s =
Joe
>> lookup( upper(s) - 'A' + 1 )
ans =
13
23
3
The key here is that Matlab allows you to index any matrix with another matrix: M(A)
. The elements of the matrix A
are treated as indices into the matrix M
. Your string s
is a char matrix, which you convert into a numeric matrix by subtracting 'A'
. The line lookup(...)
then uses the elements of this converted matrix to index the matrix lookup
.
This, incidentally, can be used for assignment as well. For example, if you wanted to keep a count of each character (independent of case):
% Initialize counts to zero somewhere at the beginning
counts = zeros(26,1);
... % do your stuff
% let 's' be an alphabetic word (only A-Z and a-z)
s_inds = upper(s) - 'A' + 1;
counts( s_inds ) = counts( s_inds ) + 1; % increment the counts of all characters in 's'