How to get all possible combinations of data in a cell?
3 views (last 30 days)
Show older comments
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 Comments
Answers (1)
José-Luis
on 10 Feb 2017
Edited: José-Luis
on 10 Feb 2017
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 Comments
See Also
Categories
Find more on Resizing and Reshaping Matrices in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!