Malinator
Malinator

Reputation: 143

How to convert a String to a Matrix Matlab

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]);

Upvotes: 0

Views: 559

Answers (1)

Luis Mendo
Luis Mendo

Reputation: 112669

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

Upvotes: 1

Related Questions