0

Im trying to convert a String into a Matrix. So like a=1 b=2... "Space"=28. Etc.

My question is how would I convert a string to a matrix?

aka.. abc=[1,2,3]

Tried a for loop, which does convert the string into numbers. Here is where I try to make it into a Matrix

String1=char(string)
String2=reshape(String1,[10,14]);

the error I get is "To RESHAPE the number of elements must not change" "String2=reshape(String1,[10,14]);

Malinator
  • 113
  • 1
  • 1
  • 5

1 Answers1

1

If you need a general coding from characters into numbers (not necessarily ASCII):

  1. Define the coding by means of a string, such that the character that appears first corresponds to number 1, etc.
  2. Use ismember to do the "reverse indexing" operation.

Code:

coding = 'abcdefghijklmnñopqrstuvwxyz .,;'; %// define coding: 'a' is 1, 'b' is 2 etc
str = 'abc xyz'; %// example text
[~, result] = ismember(str, coding);

In this example,

result =
     1     2     3    28    25    26    27
Luis Mendo
  • 110,752
  • 13
  • 76
  • 147
  • Doesn't `ismember` perform a linear search on the array, here? If so, I'm not sure this would scale well for a large alphabet. – jub0bs Mar 19 '15 at 18:12
  • @Jubobs It probably does perform a linear search on the second input, unless that second input is sorted, in which case it calls the helper mex `ismembc` or `ismembc2` functions (at least in R2010b), which deal with the sorted case more efficiently. So for large alphabets it may be slow. But in that case, how could it be done faster? – Luis Mendo Mar 19 '15 at 18:28
  • Using some kind of finite-map data structure, I suppose (like http://stackoverflow.com/questions/9850007/how-to-use-hash-tables-dictionaries-in-matlab), but I haven't tested it. – jub0bs Mar 19 '15 at 18:32