user3075021
user3075021

Reputation: 95

combine two n dimensional cell arrays into a n by n dimensional one

I wonder how to do this in MATLAB.

I have a={1;2;3} and would like to create a cell array

{{1,1};{1,2};{1,3};{2,1};{2,2};{2,3};{3,1};{3,2};{3,3}}.

How can I do this without a for loop?

Upvotes: 3

Views: 131

Answers (4)

rayryeng
rayryeng

Reputation: 104464

You can use meshgrid to help create unique permutations of pairs of values in a by unrolling both matrix outputs of meshgrid such that they fit into a N x 2 matrix. Once you do this, you can determine the final result using mat2cell to create your 2D cell array. In other words:

a = {1;2;3};
[x,y] = meshgrid([a{:}], [a{:}]);
b = mat2cell([x(:) y(:)], ones(numel(a)*numel(a),1), 2);

b will contain your 2D cell array. To see what's going on at each step, this is what the output of the second line looks like. x and y are actually 2D matrices, but I'm going to unroll them and display what they both are in a matrix where I've concatenated both together:

>> disp([x(:) y(:)])

 1     1
 1     2
 1     3
 2     1
 2     2
 2     3
 3     1
 3     2
 3     3

Concatenating both vectors together into a 2D matrix is important for the next line of code. This is a vital step in order to achieve what you want. After the second line of code, the goal will be to make each element of this concatenated matrix into an individual cell in a cell array, which is what mat2cell is doing in the end. By running this last line of code, then displaying the contents of b, this is what we get:

>> format compact;
>> celldisp(b)

b{1} =
     1     1
b{2} =
     1     2
b{3} =
     1     3
b{4} =
     2     1
b{5} =
     2     2
b{6} =
     2     3
b{7} =
     3     1
b{8} =
     3     2
b{9} =
     3     3

b will be a 9 element cell array and within each cell is another cell array that is 1 x 2 which stores one row of the concatenated matrix as individual cells.

Upvotes: 0

arccoder
arccoder

Reputation: 57

Using repmat and mat2cell

A = {1;2;3};
T1 = repmat(A',[length(A) 1]);
T2 = repmat(A,[1 length(A)]);
C = mat2cell(cell2mat([T1(:),T2(:)]),ones(length(T1(:)),1),2);

Upvotes: 0

Benoit_11
Benoit_11

Reputation: 13945

Just for fun, using kron and repmat:

a = {1;2;3}

b = mat2cell([kron(cell2mat(a),ones(numel(a),1)) repmat(cell2mat(a),numel(a),1)])

Here square brackets [] are used to perform a concatenation of both column vectors, where each is defined either by kron or repmat.

This can be easily generalized, but I doubt this is the most efficient/fast solution.

Upvotes: 1

Divakar
Divakar

Reputation: 221514

You can use allcomb from MATLAB File-exchange to help you with this -

mat2cell(allcomb(a,a),ones(1,numel(a)^2),2)

Upvotes: 1

Related Questions