1

For my code I need a changeable structure. Depending on a counter the structure should add additional fields. All fields shall be flexible and may have different values. Currently, I use a switch-condition. For transparency I would like to change this. To make an example my code below can take different values for (spl{1,i}{1}) (e.g. Input/Output,...). The latter number (1) counts until the structlength is reached. So if structlength is equal to 2, the code would look like this: testData.(spl{1,i}{1}).(spl{1,i}{2})

To sum up: Is it possible to eliminate the switch condition?

switch structLength

    case 1
        testData.(spl{1,i}{1}) = emptyMat;
    case 2
        testData.(spl{1,i}{1}).(spl{1,i}{2}) = emptyMat;
    case 3
        testData.(spl{1,i}{1}).(spl{1,i}{2}).(spl{1,i}{3}) = emptyMat;
    case 4
        testData.(spl{1,i}{1}).(spl{1,i}{2}).(spl{1,i}{3})...
            .(spl{1,i}{4}) = emptyMat;
    case 5
        testData.(spl{1,i}{1}).(spl{1,i}{2}).(spl{1,i}{3})...
            .(spl{1,i}{4}).(spl{1,i}{5}) = emptyMat;
    case 6
        testData.(spl{1,i}{1}).(spl{1,i}{2}).(spl{1,i}{3})...
            .(spl{1,i}{4}).(spl{1,i}{5}).(spl{1,i}{6}) = emptyMat;
Adriaan
  • 17,741
  • 7
  • 42
  • 75
bg_rohm
  • 11
  • 1
  • 2
    Perhaps the `swtich` could be replaced with a `for` (without `eval`). But, do you really need such a complicated nested-struct structure? – Luis Mendo Apr 12 '19 at 13:48
  • 4
    This looks like a data structure you (or whoever inherits this code) will come to hate. Consider just having 6 different structs, or using cell arrays, or basically anything with a flatter hierarchy – Wolfie Apr 12 '19 at 13:50

1 Answers1

1

The switch can be replaced by a for loop (without eval) as follows. But I suggest you go for a simpler data structure, which will make your life easier.

% Example data
emptyMat = [10 22];
structLength = 3;
spl = {{'a', 'bb', 'ccc'}};
ii = 1;

% Create the nested struct
testData = emptyMat; % Result so far. Will be wrapped into fields from inner to outer
for k = structLength:-1:1
    testData = struct(spl{1,ii}{k}, testData); % wrap into an outer field
end

Check:

>> testData
testData = 
  struct with fields:

    a: [1×1 struct]

>> testData.a
ans = 
  struct with fields:

    bb: [1×1 struct]

>> testData.a.bb
ans = 
  struct with fields:

    ccc: [10 22]

>> testData.a.bb.ccc
ans =
    10    22
Luis Mendo
  • 110,752
  • 13
  • 76
  • 147
  • This was already quite helpful. Nevertheless, spl is a matrix with over 900 cells and I run a loop for every entry. TestData will be eliminated thus every time. How can I prevent this? – bg_rohm Apr 16 '19 at 08:22
  • @bg_rohm Sorry, I'm not sure I get what you mean. Perhaps initiallize some `TestDataAll` and then, within the loop, store `TestDataAll{k} = TestData;` where `k` is the loop index – Luis Mendo Apr 16 '19 at 10:29