How to get all possible combinations of data in a cell?
3 次查看(过去 30 天)
显示 更早的评论
I have a cell with 4 rows that contains a number of data in this format:
A, B, C, D
E, F,
1, 2, 3, 4
5, 6, 7
How can i get all possible combinations (one from each row)? For example AE15, AF15, and so on..
2 个评论
回答(1 个)
José-Luis
2017-2-10
编辑:José-Luis
2017-2-10
data = {{'A', 'B', 'C', 'D'}; ...
{'E','F',};...
{1, 2, 3, 4};...
{5, 6, 7}};
cell_size = cellfun(@(x) size(x,2) ,data);
tot_elements = cell_size' * cell_size;
[I,J,K,L] = ind2sub(cell_size',1:tot_elements);
result = [cell2mat(data{1}(I)'), cell2mat(data{2}(J)'), char([data{3}{K}]+48)', char([data{4}{L}]+48)'];
EDIT Going out of my way to avoid loops and having it work for variable-size input:
data = {{'A', 'B', 'C', 'D'}; ...
{'E','F',};...
{1, 2, 3, 4};...
{5, 6, 7}};
cell_size = cellfun(@(x) size(x,2) ,data);
tot_elements = prod(cell_size);
%Turning data into a cell array of character array
is_a_number = cellfun(@(x) isnumeric(cell2mat(x)),data);
data(is_a_number) = cellfun(@(x) {char(cell2mat(x) + 48)},data(is_a_number));
data(~is_a_number) = cellfun(@(x) {cell2mat(x)},data(~is_a_number));
%Avoiding ind2sub, convoluted way of obtaining the indexes
idx = (1:numel(data));
idx_array = bsxfun(@(x,y) ceil( (mod(x-1,prod(cell_size(1:y)))+1) ./ ...
(prod(cell_size(1:y)) / cell_size(y) ) ),...
(1:tot_elements)', idx);
%Finally getting the results based on idx_array
result = cell2mat(cellfun(@(x) {data{x}(idx_array(:,x))}, num2cell(idx))')';
Not an (explicit) loop in sight but not pretty. Not very maintainable either. I won't directly understand this if I look at it down the line. Loops in this case would be clearer, IMO.
4 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Resizing and Reshaping Matrices 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!