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 this function is successful or not), the following does NOT work:

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

This sometimes returns an error, varargout {2} is undefined, since only the first variable resultAactually gets the value when the function fails. Instead, I put all the output in a single variable:

output = func(somevars);

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

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

+3
source share
2 answers
length(fieldnames(output))

Probably the best way, but I can't think about it.

+12
source

It seems Matthews answer is the best for your problem:

nFields = numel(fieldnames(output));

There is one caveat that probably does not apply to your situation, but may be interesting to know, though: even if the structure field is empty, FIELDNAMES will still return the name of this field. For example:

>> s.a = 5;
>> s.b = [1 2 3];
>> s.c = [];
>> fieldnames(s)

ans = 

    'a'
    'b'
    'c'

If you are interested in knowing the number of fields that are not empty, you can use STRUCTFUN :

nFields = sum(~structfun(@isempty,s));

STRUCT2CELL CELLFUN:

nFields = sum(~cellfun('isempty',struct2cell(s)));

2, :

nFields = numel(fieldnames(s));

3.

+3

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


All Articles