How to generate all pairs from two vectors in MATLAB using vectorised code?
You may use
a = 1:4;
b = 1:3;
result = combvec(a,b);
result = result'
You could do it by replicating the matrices using repmat
and then turning the result into a column vector using reshape
.
a = 1:4;
b = 1:3;
c = reshape( repmat(a, numel(b), 1), numel(a) * numel(b), 1 );
d = repmat(b(:), length(a), 1);
e = [c d]
e =
1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3
4 1
4 2
4 3
Of course, you can get rid of all the intermediate variables from the example above.
Try
[p,q] = meshgrid(vec1, vec2);
pairs = [p(:) q(:)];
See the MESHGRID documentation. Although this is not exactly what that function is for, but if you squint at it funny, what you are asking for is exactly what it does.
Another solution for collection:
[idx2, idx1] = find(true(numel(vec2),numel(vec1)));
pairs = [reshape(vec1(idx1), [], 1), reshape(vec2(idx2), [], 1)];