find values in an cell array
2 次查看(过去 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 中查找有关 Multidimensional Arrays 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!