Count percentage of certain number in struct
2 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
I have a 1x120 struct with 11 fields. 1 of the fields contains the condition (half of which 0, and half 1) and another field contains the accuracy (either good=1 or wrong=0).
I now want to know how many 1s are in the accuracy field for condition=1. How do I do this? Which function will I need?
I have multiple of these 1x120 structs, so I don't want to count it manually.
2 commentaires
Réponse acceptée
Voss
le 15 Fév 2024
% something similar to your 1x120 struct:
S = struct( ...
'condition',num2cell(logical(randi([0,1],1,120))), ...
'accuracy',num2cell(logical(randi([0,1],1,120))))
% number of elements of S with accuracy==1 and condition==1 (what you asked about)
n_good_condition_1 = nnz([S([S.condition]).accuracy])
% number of elements of S with accuracy==1 and condition==0
n_good_condition_0 = nnz([S(~[S.condition]).accuracy])
% number of elements of S with accuracy==0 and condition==1
n_wrong_condition_1 = nnz(~[S([S.condition]).accuracy])
% number of elements of S with accuracy==0 and condition==0
n_wrong_condition_0 = nnz(~[S(~[S.condition]).accuracy])
2 commentaires
Plus de réponses (2)
Adam Danz
le 15 Fév 2024
Modifié(e) : Adam Danz
le 15 Fév 2024
Another approach is to use groupcounts to tally the counts between the two groups.
1. Convert the structure to a table. I'll use Voss's struct example.
S = struct( ...
'condition',num2cell(logical(randi([0,1],1,120))), ...
'accuracy',num2cell(logical(randi([0,1],1,120))));
T = struct2table(S);
head(T) % show some rows of the table
2. Apply groupcounts
summaryTable = groupcounts(T,{'condition','accuracy'})
0 commentaires
Austin M. Weber
le 15 Fév 2024
You can use nnz which tells you how many non-zeros are in an array. If your struct is named s then you can extract the data you want and perform the calculations:
idx = s.Condition == 1; % Find positions where the condition = 1
accuracy = s.Accuracy(idx); % Find the accuracy values where the condition = 1
number_of_ones = nnz(accuracy); % Count number of ones in 'accuracy'
4 commentaires
Voir également
Catégories
En savoir plus sur Logical dans Help Center et File Exchange
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!