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.

© 1996–2020 John W. Eaton
Permission is granted to make and distribute verbatim copies of this manual provided the copyright notice and this permission notice are preserved on all copies.
Permission is granted to copy and distribute modified versions of this manual under the conditions for verbatim copying, provided that the entire resulting derived work is distributed under the terms of a permission notice identical to this one.
Permission is granted to copy and distribute translations of this manual into another language, under the above conditions for modified versions.
https://octave.org/doc/v6.3.0/Looping-Over-Structure-Elements.html