Matlab: Count number of structs that have a specif

2019-08-02 14:17发布

问题:

I'm dealing with Simulink Design Verifier and want to extract some information on my own. Therefore, I want to count the number of Objectives and how much of them have been satisfied.

'Objectives' is a struct itself: Objectives<1x10 struct>

Counting the number of objectives is easy:

length(fieldnames(Objectives))

The content of 'Objectives' are also structs. Each such struct has the following content:

type

status

label

Now I want to count how many elements in 'Objectives' satisfy the property

'status == Satisfied'

回答1:

Assuming that you have an array of structs, use the following code:

 nnz(strcmp({Objectives.status},'satisfied'))

If you have old Matlab version, you can use:

 nnz(strmatch('satisfied',{Objectives.status},'exact'))


回答2:

You could also use ISMEMBER. Example:

%# lets create a sample array-of-structs
v = cellstr( num2str(rand(10,1)>0.5, 'Value %d') );
s = struct('value',v);

%# count number of structs satistying a condition
num = sum( ismember(lower({s.value}), 'value 0') )

Note how I am performing case-insensitive comparison by using LOWER function.