MATLAB: How to re-code numeric variables in a table to strings

converttable

I am using Matlab version 9.1.0.441655 (R2016).
I have created a large (2496000×8) table using array2table. Although it was simpler to create the initial matrix as uniformly numeric, for analysis I would like re-code the numbers in several variables to be strings, while leaving other variable as numeric.
An example data set:
Var1=[1; 2; 1; 2; 2; 1; 1];
Var2=[2; 2; 1; 1; 1; 2; 1];
Var3=[32.1; 34.6; 56.7; 65.3; 78.6; 23.4; 43.1];
Mat=[Var1,Var2,Var3];
Table=array2table(Mat,'VariableNames',{'Var1','Var2','Var3'});
Table =
Var1 Var2 Var3
____ ____ ____
1 2 32.1
2 2 34.6
1 1 56.7
2 1 65.3
2 1 78.6
1 2 23.4
1 1 43.1
I would like to re-code the 1's and 2's in Var1 to 'Male' and 'Female', respectively and re-code the 1's and 2's in Var2 to 'Old' and 'Young', respectively. But, leave Var3 as numeric.
To result in:
Var1 Var2 Var3
________ _______ _________
'Male' 'Young' [32.1000]
'Female' 'Young' [34.6000]
'Male' 'Old' [56.7000]
'Female' 'Old' [65.3000]
'Female' 'Old' [78.6000]
'Male' 'Old' [23.4000]
'Male' 'Young' [43.1000]
I tried:
Table.Var1(strcmp(Table.Var1,1)) = {'Male'}
But that gives a conversion error:
Conversion to double from cell is not possible.

Best Answer

JLC, you say "string", but it's very likely that you would be bettter off with categorical variables. Given you're original sample data ...
>> Var1 = [1; 2; 1; 2; 2; 1; 1];
>> Var2 = [2; 2; 1; 1; 1; 2; 1];
>> Var3 = [32.1; 34.6; 56.7; 65.3; 78.6; 23.4; 43.1];
>> t = table(Var1,Var2,Var3)
t =
7×3 table
Var1 Var2 Var3
____ ____ ____
1 2 32.1
2 2 34.6
1 1 56.7
2 1 65.3
2 1 78.6
1 2 23.4
1 1 43.1
... here's what you probably want to do:
>> t.Var1 = categorical(t.Var1,1:2,{'Male' 'Female'});
>> t.Var2 = categorical(t.Var2,1:2,{'Old' 'Young'});
>> t
t =
7×3 table
Var1 Var2 Var3
______ _____ ____
Male Young 32.1
Female Young 34.6
Male Old 56.7
Female Old 65.3
Female Old 78.6
Male Young 23.4
Male Old 43.1
A few other things:
  • Don't name your table "Table". It will come back to bite you eventually.
  • No reason to concatenate [Var1,Var2,Var3] and then call array2table, which just pulls them apart. Call table directly.
  • Your "desired" result seems to have Var3 as a cell array, each cell containing a scalar double, You definitely don't want that.
  • It's possible to convert the entire table to a cell array and work on it and convert it back, as shown by ImageAnalyst. But you can work on the table directly as I showed above. The "Conversion to double from cell is not possible." errors you saw are because, as IA says, you were assigning text to only some elements of a double variable in the table. You need to assign to t.Var1 without subscripting. My code above shows that as part of converting to categorical.
  • If you really do want strings, do it like this:
genders = {'Male'; 'Female'}; t.Var1 = genders(t.Var1);
ages = {'Male'; 'Female'}; t.Var2 = ages(t.Var2);
Related Question