2012-06-28 23 views
3

矩阵我有两个向量A,B创建使用其他载体的元素在MATLAB

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

我想创建一个矩阵,将这个样子

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] 
+1

的可能重复的[Matlab的 - 生成一些向量的元素的所有可能组合(http://stackoverflow.com/questions/4165859/matlab-generate-all-possible-combinations-of-the-元素的一些向量) – Amro

回答

3

这里是另一种方式!

c = [repmat(a,numel(b),1),sort(repmat(b,numel(a),1))] 
+0

这对我来说很好! – user1487735

3

我有一种感觉有一个更好的方法,还是......

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

找到一个更好的办法:

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

克里斯·泰勒提出了更紧凑的方式:

[A B]=meshgrid(a,b); [B(:) A(:)]; 
+0

更好:'[AB] = meshgrid(a,b); [B(:) A(:)]' –

+1

我总是使用'ndgrid' - 输出顺序更有意义。 – Jonas

相关问题