find values in an cell array

6 visualizaciones (últimos 30 días)
Nikolas Spiliopoulos
Nikolas Spiliopoulos el 8 de Mayo de 2020
Comentada: Nikolas Spiliopoulos el 8 de Mayo de 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 comentarios
KSSV
KSSV el 8 de Mayo de 2020
Read about ismember
Nikolas Spiliopoulos
Nikolas Spiliopoulos el 8 de Mayo de 2020
thanks for the answer,
just wondering if there was a quicker way
anyway thanks again!!

Iniciar sesión para comentar.

Respuesta aceptada

Walter Roberson
Walter Roberson el 8 de Mayo de 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.

Más respuestas (0)

Categorías

Más información sobre Multidimensional Arrays en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by