find values in an cell array
조회 수: 4 (최근 30일)
이전 댓글 표시
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
채택된 답변
Walter Roberson
2020년 5월 8일
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.
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!