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!

A.B.A
  • 27
  • 4
  • 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. – Adriaan Apr 11 '22 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? – A.B.A Apr 11 '22 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. – Adriaan Apr 11 '22 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? – A.B.A Apr 11 '22 at 12:11
  • I have no clue what your data looks like, as you haven't added it. You've somehow created your data and stored it in a way you defined. Just refer to it to actually use it in subsequent computations. – Adriaan Apr 11 '22 at 12:12
  • for instance, the struct has the fields: a, b, c, det1, det2, det3. by using the fields function i'll get all 6 variables, but i want to use only the "det" ones. is my question clearer now? – A.B.A Apr 11 '22 at 12:17
  • Your question keeps changing and changing. Please read [ask] and [mcve], i.e. [edit] your question with a piece of code that shows what your data looks like and how you want to read it. – Adriaan Apr 11 '22 at 12:19
  • 1
    I think the two questions I linked should give you enough information to accomplish what you want. – Cris Luengo Apr 11 '22 at 13:21

0 Answers0