0

I want program a struct in Matlab for saving some parameters.

The struct's name has to change every iteration in a loop, thus in each iteration I make a new struct. Therefore I want something like this:

index={'01','02','03'}; letter={'aa','bb','cc'}; names={'Peter','John','Michael'}; for(i=1:numel(index)){ ...... strcat(str, index{i}, letter{i})(i).name = names{i}; } 

Then, when the loop has finished I have 3 structs with the next names:

- str01aa{ name = 'Peter' } - str02bb{ name = 'John' } - str03cc{ name = 'Michael' } 

My problem is that the strcat function with the bracket (i) is not good defined, and the structs are not created.

I hope you can help me.
Thanks.

3
  • Why don't you use cells to store these structs ? Commented Jun 11, 2014 at 10:29
  • This is a simple example that I want make...I need save some 'name' variables in a same struct Commented Jun 11, 2014 at 10:31
  • please post the exact problem, anyways you can try eval command , it is not recommended by many but I can't say anything else unless I look at the exact problem. Commented Jun 11, 2014 at 10:58

1 Answer 1

1

strcat(str, index{i}, letter{i})(i).name isn't a valid operation, because strcat returns a sting object, which can't possess fields. You need to make that string into a variable name using genvarname (documentation), like so:

index={'01','02','03'}; letter={'aa','bb','cc'}; names={'Peter','John','Michael'}; for(i = 1:numel(index)) { ...... genvarname(strcat('str', index{i}, letter{i}))(i).name = names{i}; } 

Note that I changed str to 'str' for consistency with your example. As a general rule, dynamically constructed variable names are bad practice because they make debugging a nightmare.

Let me make a suggestion; instead of having a bunch of structs with different, seemingly arbitrary names, why not try something like this:

index={'01','02','03'}; letter={'aa','bb','cc'}; names={'Peter','John','Michael'}; for(i = 1:numel(index)) { ...... yourStruct(i).id = strcat('str', index{i}, letter{i}); yourStruct(i).name = names{i}; } 

Either way, good luck!

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @Fletch !! The 'genvarname()' function is that I was looking for. XD

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.