bigTree
bigTree

Reputation: 2173

Displaying a string in a matrix in matlab returns ascii

I am running the following loop in matlab:

for k=1:n s(k,:) = [k,'l'] end

Instead of getting 'l', I have 108 which corresponds to its ascii.

I found several examples on how to convert a number to its ascii value. For the other way, I read that 'char' could do the trick. However, replacing 'l' by char(108) still returns me 108 instead of char.

I noticed that

for k=1:n s(k,:) = char(108) end

would display me 'l'. Why is it not the case in a matrix, and how can I solve this problem?

Upvotes: 0

Views: 983

Answers (1)

nispio
nispio

Reputation: 1744

Matlab uses dynamic typing in which it infers the type of a variable based on what you assign to it. For example try this:

x = [72 69 76 76 79 6]
y = [72 69 76 'L' 79 6]

Notice that the x becomes an array of doubles, while y becomes an array of chars. Now if you try to set

x(2) = 'A'

the array x will maintain its type. But if you set

x = [72 'A' 76 76 79 6]

then x will change its type to an array of chars. If you want to force an array to be a char array, then you can simply call char() on the entire array.

x = char([72 69 76 76 79 6])

In your case, you could just call

s = char(s)

after running through your loop. This will recast the array as chars instead of doubles.

Also, notice that you cannot mix types in your matrix. It looks like you are trying to put numbers in the first column and letters in the second. This is technically not allowed. However, as long as you cast the value in the second column back to a char when access it, you shouldn't have a problem. For example,

for k=1:n
    s(k,:) = [k,'l'];
end

first_number = s(1,1);
first_letter = char(1,2);

Will essentially let you store numbers in one column and letters in the other. You just have to make sure to cast the letter to a char whenever you access it from the matrix.

You could also consider using cells. For example

n = 26;
s = cell(n,2);
for k=1:n
    s{k,1} = k;
    s{k,2} = 'l';
end

display(s)

If you don't like the way that Matlab displays the cell array, you can still extract pieces of the array using the following notation

% Pull out individual elements
first_number = s{1,1}
first_letter = s{1,2}

% Pull out the columns as matrices
numbers_as_matrix = cell2mat(s(:,1));
letters_as_matrix = cell2mat(s(:,2));

Upvotes: 4

Related Questions