Home > database >  Create Dynamic structure variables and save them
Create Dynamic structure variables and save them

Time:05-26

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.

  1. None of the variables' names are known. It should be thus create them dynamically
  2. All the sub structs are separated by .
  3. 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

CodePudding user response:

I'll assume here you've read your file already into MATLAB here; you can use strsplit() to split your variable name on the dot, check whether the entry corresponds to a number or field name, and create your struct with those. You can use a substruct(), in combination with subsref() or subsasgn(), to do your indexing:

data = struct;  % Initialise your final structure
% Insert a loop here over all your rows
parts = strsplit(my_str, '.');  % split your string
indx = struct;
for ii = 1:numel(parts)
    if parts{ii}(1) ~= '_' || parts{ii}(end) ~= '_'
        indx(ii).type = '.';
        indx(ii).subs = parts{ii};
    else
        indx(ii).type = '()';
        indx(ii).subs = {str2double(parts{ii}(2:end-1))};
    end
end
data = subsasgn(data, indx, my_data);

I do think this is an XY problem. There's probably a better way to export your data from whatever you used to create the CSV and a better way to load it into MATLAB for later use. Please do explain how you create your CSV in the first place and what you want to do with the data in MATLAB (or in your .mat file). Repackaging CSV files to .mat files just for the thrill of it will hardly be your goal. Thus, please ask about your problem (X), rather than your attempted solution (Y), in order to get more helpful responses.

  • Related