Iterating through a structure in MATLAB without 'fieldnames'

The usual way to iterate over the structure data type in MATLAB uses the fieldnames() function, as is done in:

 mystruct = struct('a',3,'b',5,'c',9); fields = fieldnames(mystruct); for i=1:numel(fields) mystruct.(fields{i}); end 

Unfortunately, this always spawns cell data types, and I would like to use this kind of iteration for the Matlab function block in SIMULINK, which does not allow the use of cell data types for code generation reasons.

Is there a way to iterate through the structure without using data types of cells at the same time?

Octave has a neat way described at https://www.gnu.org/software/octave/doc/interpreter/Looping-Over-Structure-Elements.html

 for [val, key] = mystruct # do something esp. with 'key' end 

Does anyone know a similar way in MATLAB?

+6
source share
2 answers

When generating code using MATLAB Coder or Simulink Coder, not only mesh arrays are forbidden, but also references to structure fields using dynamic names.

Since you cannot use dynamic names, you probably should just repeat the contents of your loop body several times, one for each field name that (since you are not using dynamic names) you would know in advance.

Although this can be cumbersome from a programming point of view, I would suggest that it will probably be a little faster anyway when you generate code from it, since the code generation process should probably unroll the loop anyway.

+2
source

MATLAB structfun supported function to generate code using MATLAB Coder. If you set the 'UniformOutput' parameter to false , then the output of structfun is a structure that has the same fields as the input. The value of each field is the result of applying the supplied function descriptor to the corresponding field in the input structure.

 mystruct = struct('a',3,'b',5,'c',9); outstruct = structfun(@sin, mystruct, 'UniformOutput', false); outstruct = a: 0.1411 b: -0.9589 c: 0.4121 

So, you can write a subfunction that contains the body of the loop in your example and pass the handle of this subfunction to the structfun call.

+2
source

Source: https://habr.com/ru/post/971004/


All Articles