- publishing free software manuals
GNU Octave Manual Version 3
by John W. Eaton, David Bateman, Søren Hauberg
Paperback (6"x9"), 568 pages
ISBN 095461206X
RRP £24.95 ($39.95)

Get a printed copy>>>

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

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 = 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.

ISBN 095461206XGNU Octave Manual Version 3See the print edition