Lauren Larkin
Lauren Larkin

Reputation: 1

Replacing letters with numbers in a MATLAB array

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?

Upvotes: 0

Views: 1436

Answers (2)

Luis Mendo
Luis Mendo

Reputation: 112749

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

Upvotes: 2

GameOfThrows
GameOfThrows

Reputation: 4510

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

Upvotes: 0

Related Questions