Saving categorical using For loop

5 vues (au cours des 30 derniers jours)
SkarletSam
SkarletSam le 28 Nov 2020
Commenté : Walter Roberson le 29 Nov 2020
for a 1000x170 data set, i am trying to save each coloumn with a catergorical for ML trait selection. I have been trying to use a for loop to assign each category names, which saved as a 1x170 cell, to each respective coloumn. I get the error of "Converting Cell to categorical is not possible". My question is what kind of data type should I do for the for categorical for loop to work?
The goal with the for loop is to create 170 individual 170 100x1 categoricals and then save them as a categorical table. clsTraits is created so there is a set of predetermined names for the categoricals.
PosData = randn(1000,171);
clsTraits = randn(1,171);
for i=1:170
clsTraits(:,i) = categorical(PosData(:,i))
end
Thanks!

Réponses (1)

Walter Roberson
Walter Roberson le 28 Nov 2020
PosData = FilledTtrnPos(:,2:171);
for i = 170 : -1 : 1
clsTraits(:,i) = categorical(PosData{:,i});
end
Note that I did not pre-initialize clsTraits: Your code initialized it to numeric instead of categorical, so the categorical would have been converted back to numeric again.
Instead of pre-initializing, I loop backwards though the columns, so that the first thing assigned is clsTraits(:,170) which will automatically fill in the rest of the columns with the correct datatype.
Caution: this code is probably not going to do what you want unless every column includes every possible category. You should probably take unique(PosData{:,:}) and pass that as the second parameter to categorical() so that the categories used will be the same for all columns.
  2 commentaires
SkarletSam
SkarletSam le 28 Nov 2020
Modifié(e) : SkarletSam le 28 Nov 2020
My apologies, I should have eloborated more on the data I am working with.
The goal with the for loop is to create 170 individual 1000x1 categoricals and then save them as a categorical table. clsTraits is created so there is a set of predetermined names for the categoricals. Maybe it is not for loop that I should be using to reach the intended results?
Walter Roberson
Walter Roberson le 29 Nov 2020
When you categorical() numeric values, then internally it uses %-0.5g format to convert the values to character vectors. It then errors if the number of unique values that result is different than the number of unique numbers.
Which is to say that when you categorical() numeric values, it is a problem if two of the values are the same up to the 5th decimal digit.

Connectez-vous pour commenter.

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Produits


Version

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by