0
A = {'a','b','c','b','a',...}

A is a <1X400> cell array and I want to create a matrix from A such that if the cell is a, the matrix shows 1, if it is b, it shows as 2 in the matrix and 3 for c.

Thank you.

3 Answers 3

4

Specific Case

For a simple specific case as listed in the question, you can use char to convert all the cell elements to characters and then subtract 96 from it, which is ascii equivalent of 'a'-1 -

A_numeric = char(A)-96

Sample run -

>> A
A = 
    'a'    'b'    'c'    'b'    'a'
>> A_numeric = char(A)-96
A_numeric =
     1
     2
     3
     2
     1

Generic Case

For a generic substitution case, you need to do a bit more of work like so -

%// Inputs
A = {'correct','boss','cat','boss','correct','cat'}
newcellval = {'correct','cat','boss'}
newnumval = [8,2,5]

[unqcell,~,idx]  = unique(A,'stable')
[~,newcell_idx,unqcell_idx] = intersect(newcellval,unqcell,'stable')
A_numeric = newnumval(changem(idx,newcell_idx,unqcell_idx))

Sample input-output -

>> A,newcellval,newnumval
A = 
    'correct'    'boss'    'cat'    'boss'    'correct'    'cat'
newcellval = 
    'correct'    'cat'    'boss'
newnumval =
     8     2     5
>> A_numeric
A_numeric =
     8     5     2     5     8     2
Sign up to request clarification or add additional context in comments.

Comments

2

That's easy:

result = cell2mat(A)-'a'+1

For a generic association of letters to numbers 1,2,3...:

letters2numbers = 'abc'; %// 'a'->1, 'b'->2 etc.
[~, result] = ismember(cell2mat(A), letters2numbers)

For a generic association of strings to numbers 1,2,3...:

strings2numbers = {'hi', 'hello', 'hey', 'good morning', 'howdy'};
A = {'hello', 'hi', 'hello', 'howdy', 'bye'};
[~, result] = ismember(A, strings2numbers)

In this example,

result =
     2     1     2     5     0 

2 Comments

works very nicely but what if the cell contains a "word" such as "correct"?
@chinkare_16 Think you can use unique in that case - [~,~,out] = unique(A,'stable'). But, then what to map to what, you need to decide that.
1

use a For Loop which iterate over A and convert character to number

for loop = 1:length(A)
  outMat(loop) = char(A(loop)) - 96
end

I hope it works.

1 Comment

for loop is not necessary. This can be done vectorized. See Divakar's answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.