MartinKoch123 / yaml

MATLAB YAML parser and emitter based on SnakeYAML
MIT License
22 stars 7 forks source link

Best way to create a cell array of character vectors instead of strings #2

Closed billtubbs closed 2 years ago

billtubbs commented 2 years ago

Excellent, and useful tool. Thanks.

I'm using it to store information on variables with names. For example, my Yaml file might contain:

cvs:
  names: [SAG_WT, SAG_POW, SAG_CC, SAG_OF_P80]

After loading the yaml file to a struct called model_data these names become a cell array as expected:

>> model_data.cvs.names

ans =

  1×4 cell array

    {["SAG_WT"]}    {["SAG_POW"]}    {["SAG_CC"]}    {["SAG_OF_P80"]}

However, tables don't seem to accept cell arrays of strings and seem to require char

>> array2table(rmse, 'VariableNames', model_data.cvs.names)
Error using table (line 326)
The VariableNames property is a cell array of character vectors. To assign multiple variable names, specify names in a string
array or a cell array of character vectors.

Is there a way to force a cell array of character vectors instead of strings? Or, any other ideas on how to easily populate the RowNames or VariableNames properties of tables?

billtubbs commented 2 years ago

The only way I've found to convert them is this, but its not very pretty...

cv_names = convertStringsToChars([model_data.cvs.names{:}]);
MartinKoch123 commented 2 years ago

Hey, you can use cellstr to convert a cell of strings to a cell of char arrays.

Also, they implemented string array support for tables somewhere between R2018a and R2021b if upgrading is an option for you. In that case you could set the ConvertToArray option of yaml.loadFile to true to get an array of strings, which you can pass to table.

billtubbs commented 2 years ago

Thanks very much. Didn't know about cellstr. Also, yes I need to upgrade. I'm still using R2019b.