For a loop to retrieve information from a structure doesn't work?

I have a structure in matlab that matters <1x1 struct>.

, its name figurelist

. Inside this structure, there is a field called images

. Inside the images I have 25 images namedimg1, img2, img3, ..... , img25.

Now I made a for loop to fetch these images, I basically did:

 For K=1:25
     image(figurelist.images.imgK)
     PAUSE(0.25)
 End

      

This, unfortunately, does not work. I am getting the error:

??? Reference to non-existent field 'imgK'.

Is it possible to extract such information using a loop from a structure? Or am I doing something wrong? Thanks.

+2


a source to share


2 answers


You would need to do something like this:

for K=1:25
  image(figurelist.images.(['img' int2str(K)]))
  pause(0.25)
end

      



Since the field name is a function of your loop variable, you must construct a string for the field name. The INT2STR function converts the value of your loop variable K

to a character string, which is then appended to 'img'

to create a string for the field name. The dynamic field reference syntax ( .( )

) is then used to access the field value using that string .

Some good examples of using dynamic field names can be found on Lauren's feed and Doug's blog .

+4


a source


I believe you are looking for dynamic field names: http://www.mathworks.com/access/helpdesk/help/techdoc/matlab_prog/br04bw6-38.html#br1v5cc-1



+2


a source







All Articles