manpagez: man pages & more
info octave
Home | html | info | man
[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

10.5.1 Looping Over Structure Elements

A special form of the for statement allows you to loop over all the elements of a structure:

 
for [ val, key ] = expression
  body
endfor

In this form of the for statement, the value of expression must be a structure. If it is, key and val are set to the name of the element and the corresponding value in turn, until there are no more elements. For example,

 
x.a = 1
x.b = [1, 2; 3, 4]
x.c = "string"
for [val, key] = x
  key
  val
endfor

     -| key = a
     -| val = 1
     -| key = b
     -| val =
     -| 
     -|   1  2
     -|   3  4
     -| 
     -| key = c
     -| val = string

The elements are not accessed in any particular order. If you need to cycle through the list in a particular way, you will have to use the function fieldnames and sort the list yourself.

The key variable may also be omitted. If it is, the brackets are also optional. This is useful for cycling through the values of all the structure elements when the names of the elements do not need to be known.


© manpagez.com 2000-2024
Individual documents may contain additional copyright information.