Saving categorical using For loop
2 次查看(过去 30 天)
显示 更早的评论
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!
0 个评论
回答(1 个)
Walter Roberson
2020-11-28
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 个评论
Walter Roberson
2020-11-29
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.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Categorical Arrays 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!