views:

51

answers:

2

I have a structure in matlab that has a value of <1x1 struct>., its name is figurelist. Inside that structure, there is a field called images. Inside images, I have 25 images that have the name img1, img2, img3, ..... , img25.

Now I made a for loop to extract those images, I basically did:

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

This unfortunately doesnt work. I get an error saying :

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

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

+4  A: 

You would have 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 have to construct a string for the field name. The function INT2STR converts the value of your loop variable K to a character string, which is then appended to 'img' to create the string for the field name. Then the dynamic field reference syntax (.( )) is used to access the field value using that string.

A couple of nice examples of using dynamic field names can be found on Loren's blog and Doug's blog.

gnovice
Thanks that fixed the problem ( I have to wait 10 mins before accepting) ... Can you please explain what you did ? You put integer to string conversion of K .. why ? So it can read it as a value rather than a character ?? or what
ZaZu
Thanks for explaining :)
ZaZu
Doug's blog was so helpful !! thanks !!
ZaZu
+2  A: 

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

weiy
Thanks for directing me to that link :)
ZaZu