create a vector ,of sets of predefined numbers stored in another row vectors

조회 수: 1 (최근 30일)
Guys,I have two row vectors X=[3:6] and Y=[8:27].I want to create and store all possible combinations of (X,Y) in another vector ,say Z.
So my Z will be, Z=[(3,8) (3,9) (3,10)...(3,27) (4,8) (4,9)......(6,26) (6,27)]

채택된 답변

Guillaume
Guillaume 2015년 3월 3일
This is called the Cartesian product of the two sets.
A fairly straightforward way is to use ndgrid:
x = 3:6;
y = 8:27;
[xx, yy] = ndgrid(x, y);
cartprod = [xx(:) yy(:)]
This works also for more than two vectors:
x = 3:6;
y = 8:27;
z = 2:2:8;
[xx, yy, zz] = ndgrid(x, y, z);
cartprod = [xx(:) yy(:) zz(:)]
  댓글 수: 3
Ace_ventura
Ace_ventura 2015년 3월 3일
Just one more thing. I want to extract 3rd set i.e. (5,8)..however when i tried cartprod(3),it gives me 5. I want to obtain that set value i.e. 5 and 8
Guillaume
Guillaume 2015년 3월 3일
cartprod(3, :)
You want all the columns (:) of the 3rd row

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

James Tursa
James Tursa 2015년 3월 3일
편집: James Tursa 2015년 3월 3일
Not sure how you want the answer actually stored (the syntax in your example isn't clear), but here is one way:
XX = repmat(X(:)',numel(Y),1);
YY = repmat(Y(:),1,numel(X));
Z = [XX(:) YY(:)];

카테고리

Help CenterFile Exchange에서 MATLAB에 대해 자세히 알아보기

태그

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by