All combinations of cell arrays

2 views (last 30 days)
Hello! I have several matrices of different sizes, which i want to combine per row.
For example i have these ones:
A= [1 2 3 B= [1 6
1 2 4 4 5]
1 3 5]
As an ouput i would like to have:
C= [1 2 3 1 6
1 2 3 4 5
1 2 4 1 6
1 2 4 4 5
1 3 5 1 6
1 3 5 4 5]
I tried to convert it into two cell arrays and use ndgrid, but something doesn't work and i get the wrong combinations.
Thanks in advance!
  1 Comment
Jan
Jan on 16 Mar 2022
There are no cell arrays in the question, but 2 matrices.

Sign in to comment.

Accepted Answer

Walter Roberson
Walter Roberson on 16 Mar 2022
A= [1 2 3
1 2 4
1 3 5];
B = [1 6
4 5];
nA = size(A,1);
nB = size(B,1);
[Aidx, Bidx] = meshgrid(1:nA, 1:nB);
C = [A(Aidx,:), B(Bidx,:)]
C = 6×5
1 2 3 1 6 1 2 3 4 5 1 2 4 1 6 1 2 4 4 5 1 3 5 1 6 1 3 5 4 5

More Answers (1)

Jan
Jan on 16 Mar 2022
Edited: Jan on 16 Mar 2022
A = [1 2 3; ...
1 2 4 ; ...
1 3 5];
B = [1 6; ...
4 5];
C = [repelem(A, size(B, 1), 1), ...
repmat(B, size(A, 1), 1)]
C = 6×5
1 2 3 1 6 1 2 3 4 5 1 2 4 1 6 1 2 4 4 5 1 3 5 1 6 1 3 5 4 5

Categories

Find more on Matrices and Arrays in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!