简体   繁体   中英

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.

length(fieldnames(output))

可能有更好的方法,但我想不出来。

It looks like Matthews answer is the best for your problem:

nFields = numel(fieldnames(output));

There's one caveat which probably doesn't apply for your situation but may be interesting to know nonetheless: even if a structure field is empty, FIELDNAMES will still return the name of that 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 could use either STRUCTFUN :

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

or a combination of STRUCT2CELL and CELLFUN :

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

Both of the above return an answer of 2, whereas:

nFields = numel(fieldnames(s));

returns 3.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM