![](/img/trans.png)
[英]MATLAB - avoiding loops to create a matrix based on the elements of other vectors
[英]Create a matrix using elements of other vectors in matlab
我有两个向量a,b
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]
这是另一种方式!
c = [repmat(a,numel(b),1),sort(repmat(b,numel(a),1))]
我觉得还有更好的方法,还是......
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(:)];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.