0

I am trying to write a function to mark the results of a test. The answers given by participants are stored in a nx1 cell array. However, theses are stored as letters. I am looking for a way to convert (a-d) these into numbers (1-4) ie. a=1, b=2 so these can be compared the answers using logical operations.

What I have so far is:
[num,txt,raw]=xlsread('FolkPhysicsMERGE.xlsx', 'X3:X142');
FolkPhysParAns=txt;

I seem to be able to find how to convert from numbers into letters but not the other way around. I feel like there should be a relatively easy way to do this, any ideas?

Mark Cidade
  • 98,437
  • 31
  • 224
  • 236
  • you can use strrep to replace 'a' with '1' (note it is the string format), and do it for all 26 letters and then use cell2mat to convert string '1' - '26' etc to numeric 1 -26. – GameOfThrows Sep 02 '15 at 10:02
  • What is exactly the type of that nx1 array? Can you edit the question to include an example? – Luis Mendo Sep 02 '15 at 10:06
  • Okay, I have tried to add the info, let me know if it is not what you need. – Lauren Larkin Sep 02 '15 at 10:12
  • Thanks @GameOfThrows that worked! – Lauren Larkin Sep 02 '15 at 10:16
  • I found this [similar question][1] here, in stack overflow, I think it could help you: [1]: http://stackoverflow.com/questions/7606439/mapping-letters-to-integers-in-matlab – Alex Sep 02 '15 at 10:17

2 Answers2

2

If you have a cell array of letters:

>> data = {'a','b','c','A'};

you only need to:

  1. Convert to lower-case with lower, to treat both cases equally;
  2. Convert to a character array with cell2mat;
  3. Subtract (the ASCII code of) 'a' and add 1.

Code:

>> result = cell2mat(lower(data))-'a'+1
result =
     1     2     3     1

More generally, if the possible answers are not consecutive letters, or even not single letters, use ismember:

>> possibleValues = {'s', 'm', 'l', 'xl', 'xxl'};
>> data = {'s', 'm', 'xl', 'l', 'm', 'l', 'aaa'};
>> [~, result] = ismember(data, possibleValues)
result =
     1     2     4     3     2     3     0
Luis Mendo
  • 110,752
  • 13
  • 76
  • 147
0

Thought I might as well write an answer... you can use strrep to replace 'a' with '1' (note it is the string format), and do it for all 26 letters and then use cell2mat to convert string '1' - '26' etc to numeric 1 -26.

Lets say:

t = {'a','b','c'} //%Array of Strings
t = strrep(t,'a','1') //%replace all 'a' with '1' 
t = strrep(t,'b','2') //%replace all 'b' with '2'
t = strrep(t,'c','3') //%replace all 'c' with '3'
%// Or 1 line:
t = strrep(g,{'a','b','c'},{'1','2','3'})
>> t = 

'1'    '2'    '3'

output = cellfun(@str2num,t,'un',0)  //% keeps the cell structure

>> output = 

[1]    [2]    [3]

alternatively:

output = str2num(cell2mat(t'))   //% uses the matrix structure instead, NOTE the inversion ', it is crucial here.

>> output =
 1
 2
 3
GameOfThrows
  • 4,510
  • 2
  • 27
  • 44