Change a column of data in a variable from numeric to a string value
조회 수: 2 (최근 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!