osm
osm

Reputation: 622

Using Cell Array Contents to Create Struct Entries

Say that I have two cell arrays, A and B, that contain string values. I wish to populate a struct S such I generate every possible combination of S.valueinA.valueinB = 1. I am currently trying to accomplish this with two nested for-loops that iterate through every possible combination and wanted to ask if there is a more efficient way to solve this problem in MATLAB.

Upvotes: 1

Views: 77

Answers (1)

rayryeng
rayryeng

Reputation: 104503

If you want to make dynamic field names in structures, I don't see how else you can do it without two for loops. Let's say we have two cell arrays A and B that consist of string entries. For my example, apologies for the strings inside these arrays in advance as I couldn't think of anything better at the moment!

Is this what you're trying to achieve?

S = struct();
A = {'hello', 'my', 'name', 'is', 'ray'};
B = {'i', 'am', 'doing', 'awesome'};
for idx = 1 : numel(A)
    for idx2 = 1 : numel(B)
        S.(A{idx}).(B{idx2}) = 1;
    end
end

This creates a nested structure S such that for each element in A, this becomes a field in S where this field is another structure that contains fields with names coming from all elements in B.

If we displayed S, we get:

>> S

S = 

    hello: [1x1 struct]
       my: [1x1 struct]
     name: [1x1 struct]
       is: [1x1 struct]
      ray: [1x1 struct]

If we accessed the hello field of S, we get:

>> S.hello

ans = 

          i: 1
         am: 1
      doing: 1
    awesome: 1

Similarly, if we accessed the my field, we get:

>> S.my

ans = 

          i: 1
         am: 1
      doing: 1
    awesome: 1

Therefore, if we want to get the hello field followed by the am field, we do:

>> S.hello.am

ans =

     1

Upvotes: 3

Related Questions