3

I have two vectors a, b

a=[1; 2; 3; 4]
b=[1; 2; 3] 

And I want to create a matrix which will look like this

c=[1 1; 2 1; 3 1; 4 1; 1 2; 2 2; 3 2; 4 2; 1 3; 2 3; 3 3; 4 3]
Amro
  • 123,847
  • 25
  • 243
  • 454
user1487735
  • 81
  • 1
  • 8
  • 1
    possible duplicate of [Matlab - Generate all possible combinations of the elements of some vectors](http://stackoverflow.com/questions/4165859/matlab-generate-all-possible-combinations-of-the-elements-of-some-vectors) – Amro Jun 29 '12 at 16:03

2 Answers2

4

Here is yet another way!

c = [repmat(a,numel(b),1),sort(repmat(b,numel(a),1))]
Not Bo Styf
  • 411
  • 5
  • 11
3

I have a feeling that there is a much better way, still...

p1 = repmat(a,[numel(b),1]);
p2 =  imresize(b,[numel(a)*numel(b) 1],'nearest');
answer =  [p1 p2];

Found a better way:

 [A,B] = meshgrid(a,b);
 answer = [reshape(B,[],1) reshape(A,[],1)];

Chris Taylor suggests a more compact way:

 [A B]=meshgrid(a,b); [B(:) A(:)];
Andrey Rubshtein
  • 20,795
  • 11
  • 69
  • 104