0

I have a struct res with the variables: det1, det2, det3. I also have the amount of these variables (in this case 3), and I want to read them in a loop. How can I integrate the iteration variable in the name of the variables in the loop and read them? I want to do something like this:

for i=1:num_variables
    var_name = 'res.det'+num2str(i);
    % read var_name
end 

Thanks for the help!

8
  • Please don't do this! This is a very, very, very bad habit, prone to errors, slow code etc (see the links in the duplicate target). Instead, rethink your approach, probably you should simply keep the struct variable and read that using your loop. Commented Apr 11, 2022 at 11:46
  • thanks for the advise. however, i don't create new variables and just read them. also, the number of variables can change so that the loop over the number of them helps to write the code in a general form. how would you do that? Commented Apr 11, 2022 at 12:00
  • You get all the fields by your_fields = fields(your_struct), you can then loop over that array, e.g. res.your_fields(ii). What do you mean by "reading" them? If you have a structure, the data stored within is already loaded into MATLAB, i.e. usable. All you need to do is refer to it. Commented Apr 11, 2022 at 12:06
  • by reading i mean using it. the struct has other fields and not only the ones that i mentioned above. i can i use only the ones i need using your way? Commented Apr 11, 2022 at 12:11
  • 1
    I think the two questions I linked should give you enough information to accomplish what you want. Commented Apr 11, 2022 at 13:21

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.