How to convert characters in a table into numbers

27 visualizaciones (últimos 30 días)
Erik Michael
Erik Michael el 6 de Feb. de 2020
Comentada: Erik Michael el 6 de Feb. de 2020
So i have a large table full of cloud cover codes from weather station reports. What I want to do is convert said codes into a corresponding number. For example, I want all 'CLR' reports to return a value of zero, 'FEW' to return a value of 1, and so forth. An example of the results I'm looking for:
'SCT' ---> 2
'OVC' ---> 4
'BKN' ---> 3
'CLR' ---> 0
  4 comentarios
Adam Danz
Adam Danz el 6 de Feb. de 2020
Duplicates shouldn't be a problem. What's the full copy-pasted error message?
Erik Michael
Erik Michael el 6 de Feb. de 2020
Here's my code:
Array = table2cell(B);
Cat = categorical(Array);
C = categorical(Cat,['CLR' 'FEW' 'SCT' 'BKN' 'OVC'],[0 1 2 3 4]);
And here's the error:
Error using categorical (line 340)
VALUESET contains duplicated values.
Error in (line 17)
C = categorical(Cat,['CLR' 'FEW' 'SCT' 'BKN' 'OVC'],[0 1
2 3 4]);

Iniciar sesión para comentar.

Respuesta aceptada

Guillaume
Guillaume el 6 de Feb. de 2020
a) There's rarelly any need of table2cell or table2array. These are usually used by people who don't know how to index into table (using . indexing or {} indexing).
b) in your code, Cat is already a categorical that you created with categorical(Array). You can't convert that to another categorical
c) In the 2nd call to categorical, you've got the order of value set and category set reverse. A proper call would be:
c = categorical(numericarray, 0:4, {'CLR', 'FEW', 'SCT', 'BKN', 'OVC'});
d) Remember that 'CLR' is a 1x3 char vector and that [] is the concatenation operator, so ['CLR' 'FEW'] just concatenates two char vectors into 'CLRFEW'. So indeed, you passed 'CLRFEWSCTBKNOVC' as the value set which has many duplicate letters.
If you want to create an array of char vectors you need to use a cell array as I have done above. Or you can use a string array: ["CLR", "FEW", "SCT", "BKN", "OVC"] note the use of " instead of '.
Anyway, it sounds like you want to convert a cell array of char vectors into numeric values. If so, you can't use categorical for that, at least not straight away:
cats = {'CLR', 'FEW', 'SCT', 'BKN', 'OVC'}
vals = 0:4;
[found, where] = ismember(yourcellarrayofchar, cats);
assert(all(found), 'Some entries are not present in cats')
numarray = vals(where);
numvalues can then be converted to categorical given you the best of both worlds:
catarray = categorical(numarray, vals, cats);
Since you can treat it as either character or numeric
double(catarray) == 1 %which elements of the array have numerical value 1
catarray == 'FEW' %which elements of the array have text FEW

Más respuestas (0)

Categorías

Más información sobre File Name Construction en Help Center y File Exchange.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by