views:

1445

answers:

4

If I have a vector, for example: V = [ 1, 2, 3, 4 ]. Is there a way to change this to the letters [ a,b,c,d ]?

+1  A: 

Something like

C = char(V+ones(size(V)).*(97-1))

should work (97 is the ASCII code for 'a', and you want 1 to map to 'a' it looks like).

Matt J
+1  A: 

Using the CHAR function, which turns a number (i.e. ASCII code) into a character:

charString = char(V+96);

EDIT: To go backwards (mapping 'a' to 1, 'b' to 2, etc.), use the DOUBLE function to recast the character back to its ASCII code number:

V = double(charString)-96;
gnovice
thanks that worked perfectly
could you tell me how to do the reverse?
+1  A: 

There are two simple ways to do this. One way is a simple index.

C = 'abcdefghijklmnopqrstuvwxyz';
V = [8 5 12 12 15 23 15 18 12 4];

C(V)
ans =
helloworld

Of course, char will do it too. The char answer is better because it does not require you to store a list of letters to index into.

char('a' + V - 1)
ans =
helloworld

This is best since when you add 'a' to something, it converts 'a' to its ascii representation on the fly. +'a' will yield 97, the ascii form of 'a'.

A nice thing is it also works for 'A', so if you wanted caps, just add 'A' instead.

char('A' + V - 1)
ans =
HELLOWORLD

You can find more information about working with strings in MATLAB from these commands:

help strings
doc strings
woodchips
char() is also prefereable in the case that the order of the letters changes at some point in the future...
Revah
+6  A: 

Using 'a' directly instead of ascii codes might be slightly more readable

charString = char(V-1+'a');

Uppercase is then obtained with

charString = char(V-1+'A');
Fanfan
blast! i figured this would work, but didn't have a copy of matlab handy to make sure. good show :)
Matt J

related questions