Search code examples
matlabmatlab-struct

How can I count the number of properties in a structure in MATLAB?


I have a function that returns one or more variables, but as it changes (depending on whether the function is successful or not), the following does NOT work:

[resultA, resultB, resultC, resultD, resultE, resultF] = func(somevars);

This will sometimes return an error, varargout{2} not defined, since only the first variable resultA is actually given a value when the function fails. Instead I put all the output in one variable:

output = func(somevars);

However, the variables are defined as properties of a struct, meaning I have to access them with output.A. This is not a problem in itself, but I need to count the number of properties to determine if I got the proper result.

I tried length(output), numel(output) and size(output) to no avail, so if anyone has a clever way of doing this I would be very grateful.


Solution

  • length(fieldnames(output))
    

    There's probably a better way, but I can't think of it.