views:

179

answers:

3

If I am given a string of letters abcd and I want to convert this to a vector V = [ 1,2,3,4], how can I do this?

A: 

use uint8, then subtract the char value of 'a', then push that onto a vector. http://www.google.com/search?hl=en&client=firefox-a&rls=org.mozilla%3Aen-US%3Aofficial&q=matlab%2Bstring%2Bmanipulation%2Baccess%2Bchar&btnG=Search">link

geowa4
A: 

To map 'a' to 1, 'b' to 2, etc., use the DOUBLE function to recast the character back to its ASCII code number, then shift the value:

V = double(charString)-96;

EDIT: Actually, you don't even need the call to DOUBLE. Characters will automatically be converted into double-precision numbers when you perform any arithmetic with another double-precision number (the default type for MATLAB variables). So, the following is an even simpler answer:

V = charString-96;
gnovice
+4  A: 

Just subtract 'a'. Add one to map 'a' to 1. The subtraction sends the results into a double.

V = C - 'a' + 1;

For example,

C = 'helloworld';
C - 'a' + 1
ans =
     8     5    12    12    15    23    15    18    12     4
woodchips
Thanks woodchips, found that an interesting 'trick' :)
ccook
+1 I thought that might work, but I wasn't at a machine with MATLAB to test it.
gnovice

related questions