简体   繁体   中英

Create a matrix using elements of other vectors in matlab

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]

这是另一种方式!

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

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(:)];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM