1

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.

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

3 Comments

@nkjt - lol. thank you very much. that comment made my morning.
@rayryeng Thanks for the answer! This is in fact what I was trying to achieve; I was trying to research whether matlab had a more efficient method (since this could take really long over thousands of entries).
@mCode - Ah I gotcha. Yeah when it comes to dynamic field names, I don't see how you could do this without a for loop. However, if the nested field consists of just a single number, then I think it should be relatively fast. I haven't tested it yet, but that's my hunch. You're welcome btw!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.