Daniel Griffiths
Daniel Griffiths

Reputation: 11

Why do I get this error inserting a character into a MATLAB matrix?

I am constructing a 16x16 matrix, consisting of just letters in MATLAB. I tried for example:

for i=1:2:3
    C(i,2)=char('B');    
end

to place the letter 'B' in its corresponding place in the matrix. However this gives a value of 66 in the matrix instead of just the letter 'B'. What is going wrong?

Upvotes: 1

Views: 8162

Answers (3)

gnovice
gnovice

Reputation: 125874

The problem is most likely that you already have a variable called C that contains numeric data in it. When you try to place a character into a numeric matrix, the character gets converted to its ASCII value. If you clear the variable C before running your above code, you should get a character matrix for C:

>> clear C
>> for i=1:2:3, C(i,2) = 'B'; end
>> C

C =

 B

 B

Note in this case that C is a 3-by-2 array with null characters (ASCII code 0) in the first column and second row of the second column. If you want to initialize C to be a 16-by-16 character array of null characters, you can replace the CLEAR statement in the above code with:

C = char(zeros(16));

And then run your loop to fill in your values. Also note that char('B') is redundant, since 'B' is already of type character.

Upvotes: 1

abcd
abcd

Reputation: 42225

If I do

for i=1:3
    C(i)=char('A');
end

I get C=AAA, as you'd expect. I suspect the reason why you're getting the decimal value of the char is because you might have preallocated C as C=zeros(16). MATLAB initialized the array as numeric type and accordingly, when you replaced an element with a char, it promptly converted it to its numeric value.

A better approach would be to use cells and then convert it to a matrix.

C=cell(4,4);%# create an empty 4x4 cell
for i=1:16
    C{i}=char('A');
end

C=


    'A'    'A'    'A'    'A'
    'A'    'A'    'A'    'A'
    'A'    'A'    'A'    'A'
    'A'    'A'    'A'    'A'

Now use cell2mat to convert it to a matrix:

Cmatrix=cell2mat(C)

Cmatrix=

    AAAA
    AAAA
    AAAA
    AAAA

Normally, I wouldn't use loops, but I don't know your exact requirements, so I've shown an example as per your question.

Upvotes: 0

user492238
user492238

Reputation: 4084

Matlab stores the letter 'B' as integer ASCII code. Ini fact, char means int8.

Upvotes: 0

Related Questions