For my program input is a csv file with some variable names and their values.
| var name | value |
| -------- | -------------- |
| a.b | 345 |
| a.c._0_.field1 | 322 |
| a.c._0_.field2 | 5 |
| a.c._1_.field1 | 32 |
| a.c._1_.field2 | 50 |
In my code, I want to read this file and create struct variables with value mentioned in the file with following constraints.
- None of the variables' names are known. It should be thus create them dynamically
- All the sub structs are separated by
. - And in case of array, different indexes are mentioned with
_%d%_.
In above case, struct a will have data:
a.b = 345
a.c(1).field1 = 322
a.c(1).field2 = 5
a.c(2).field1 = 32
a.c(2).field2 = 50
How can I create struct named a and save to mat file?
I could do it using eval however, since it is not recommended, I was wondering if same could be achieved using setfield getfield
awithout usingeval. Otherwise, all fields can be set as usual; simply read in your file, grab the string in the first column,strplit('.'), then use each string as a field name:my_struct.splitted_string(1)etc. Given you changed the CSV after your previous question, I suspect this is an XY problem. There might well be a better way to get your data into MATLAB than creating this CSV file.eval, but it's just a really bad idea, for many reasons. I suggest instead that you create a structdata, containing all these variables:data.a.b,.data.a.c(1).field1, etc.substructandsubsasgn.datastruct. and when I save it likesave('out.mat', '-struct', 'data')a gets stored as it is.