MATLAB: Change a column of data in a variable from numeric to a string value

change variableMATLABmismatchnum2strstring

Hello,
I have a variable (Gc) containing a range of data but only 2 columns (177,2). I want to change all the numeric entries in the 2nd column to display the word 'Good' where the number '1' occurs. I have tried this code below – but get the error that follows:
Gc(Gc(:,2)== 1, 2 ) = 'Good' ;
error -- Subscripted assignment dimension mismatch.
I understand that this is saying the value 'Good' is bigger then the value '1' so it won't fit. I have also looked at using num2string to help solve this – but I cannot make sense of it.
Once again community – any help or ideas please?
Regards,
10B.

Best Answer

There are several points to mention actually. You have to differentiate numeric arrays from cell arrays (many posts or help pages are available for that). Numeric arrays can only contain numbers, homogeneous in type/class (e.g. only double, only uint8). On the contrary, a cell array is an array of cells, and each cell can contain an arbitrary content (e.g. one cell contains a numeric array, another a cell array, and a third a string). Cells arrays are hence much more flexible than numeric arrays, but they cannot be used for direct e.g. matrix computation.
Therefore, if Gc is a numeric array, you need to convert it into a cell array first. Here is an example:
>> Gc = [3, 1; 2, 0; 4, 1] % Dummy Gc for the example.
Gc =
3 1
2 0
4 1
Check the type/class:
>> class( Gc )
ans =
double
it is a numeric array of doubles. Create a cell array whose cells contain elements of the initial numeric array:
>> Gc_cell = num2cell( Gc )
Gc_cell =
[3] [1]
[2] [0]
[4] [1]
Check the type/class:
>> class( Gc_cell )
ans =
cell
Now this is a cell array, and cells can contain e.g. the string 'Good' that you want to store. Perform replacement:
>> Gc_cell(Gc(:,2)==1, 2) = {'Good'}
Gc_cell =
[3] 'Good'
[2] [ 0]
[4] 'Good'
Here, we use a logical index based on the original Gc numeric array, and we replace all indexed cells with the cell {'Good'}. When you'll read more about cell arrays versus numeric arrays, you will see how we create a cell, the difference between () and {} indexing, etc.