Got Questions? Get Answers.
Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

Thread Subject:
2-by-n coordinate matrix from x-y vectors

Subject: 2-by-n coordinate matrix from x-y vectors

From: Zeph Davies

Date: 21 Aug, 2012 12:03:08

Message: 1 of 4

Hi, i'd like to generate a 2-by-n matrix, which is basically the index list of x-y points, from the individual x and y vectors, in a fast way.

For example, if my vectors are:
x = [x1,x2,x3,...]
y = [y1,y2,y3,...]

I want the output (or something similar):
XY = [
1 1
1 2
1 3
1 ...
2 1
2 2
2 3
2 ...
3 1
3 2
3 3
3 ...
... ...]

So a list of all the combinations of x and y.

Currently, i'm using a nested for-loop, which is not always efficient.

XY = zeros(length(x)*length(y),2);
c=0;
for i = 1:length(x)
  for j = 1:length(y)
    c=c+1;
    XY(c,:)=[i,j];
  end
end

Is there a better way?

Thanks,

Subject: 2-by-n coordinate matrix from x-y vectors

From: Steven_Lord

Date: 21 Aug, 2012 13:44:21

Message: 2 of 4



"Zeph Davies" <matlab@zephmail.co.uk> wrote in message
news:k0vtds$lh7$1@newscl01ah.mathworks.com...
> Hi, i'd like to generate a 2-by-n matrix, which is basically the index
> list of x-y points, from the individual x and y vectors, in a fast way.
>
> For example, if my vectors are:
> x = [x1,x2,x3,...]
> y = [y1,y2,y3,...]
>
> I want the output (or something similar):
> XY = [
> 1 1
> 1 2
> 1 3
> 1 ...
> 2 1

*snip*

Look at MESHGRID or NDGRID.

--
Steve Lord
slord@mathworks.com
To contact Technical Support use the Contact Us link on
http://www.mathworks.com

Subject: 2-by-n coordinate matrix from x-y vectors

From: Bruno Luong

Date: 21 Aug, 2012 13:53:08

Message: 3 of 4

n = 5;
[I J]=meshgrid(1:n);
XY = [I(:) J(:)]

% Bruno

Subject: 2-by-n coordinate matrix from x-y vectors

From: Zeph Davies

Date: 21 Aug, 2012 14:01:10

Message: 4 of 4

"Bruno Luong" <b.luong@fogale.findmycountry> wrote in message <k103s4$h73$1@newscl01ah.mathworks.com>...
> n = 5;
> [I J]=meshgrid(1:n);
> XY = [I(:) J(:)]
>
> % Bruno

Thanks.
I sort of guessed it was ndgrid/meshgrid, but couldn't extract from it what i wanted.

Tags for this Thread

What are tags?

A tag is like a keyword or category label associated with each thread. Tags make it easier for you to find threads of interest.

Anyone can tag a thread. Tags are public and visible to everyone.

Contact us