find values in an cell array
4 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Nikolas Spiliopoulos
le 8 Mai 2020
Commenté : Nikolas Spiliopoulos
le 8 Mai 2020
Hi all,
I have an cell array that is like the one in the screenshot (see attached file).
I would like to find in each row, how many times value 1,2,3..etc exists
Could you help me with that?
thanks in advance!
Nikolas
2 commentaires
Réponse acceptée
Walter Roberson
le 8 Mai 2020
cell_rows = arrayfun(@(ROW) horzcat(YourCell{ROW,:}), 1:size(YourCell,1), 'uniform', 0);
all_values = horzcat(cell_rows{:});
[G, uvals] = findgroups(all_values);
num_vals = length(uvals);
row_lens = cellfun(@length, cell_rows);
G_by_row = mat2cell(G, 1, row_lens);
counts = cellfun(@(R) [uvals(:), accumarray(R(:), 1, [num_vals 1])], G_by_row, 'uniform', 0);
The result will be a cell array with 63 entries. Each entry will be an N x 2 table, where N is the number of unique values over the entire matrix (not the number of unique for the individual row.) The first column will be the list of unique values; this will be the same for all of the arrays. The second column will be the counts for the corresponding values.
This will work even if the values stored in the array are not positive integers. It will even work if the values are not integers; however in the way it is written, it will consider two values to be different if they differ in even a single bit (so if the values were calculated and there might be round-off, there could be a problem.)
If you know that the values are all positive integers in the range 1 to something (such as 50) then the code can be simplified.
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Logical dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!