bg_rohm
bg_rohm

Reputation: 11

Flexible struct name without switch

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;

Upvotes: 1

Views: 64

Answers (1)

Luis Mendo
Luis Mendo

Reputation: 112659

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

Upvotes: 1

Related Questions