Change a column of data in a variable from numeric to a string value
8 次查看(过去 30 天)
显示 更早的评论
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.
0 个评论
采纳的回答
Cedric
2015-9-10
编辑:Cedric
2015-9-10
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.
2 个评论
Cedric
2015-9-15
My pleasure! It's not that uncommon that people don't really know cell arrays, because they are not really relevant for doing purely numerical computations. In fact they start to be relevant when one needs to manage the rest: mixed data types, imports/exports, etc.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Characters and Strings 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!