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

Convert xy Coordinates to Matrix

Asked by John on 26 May 2013

I have an xy coordinates positions (100x2) and another z vector (100x1) with values corresponding to each xy coordinate. How can I make a matrix of the coordinates with the position of each coordinate having the corresponding z value? Thanks!




No products are associated with this question.

2 Answers

Answer by Andrei Bobrov on 27 May 2013
Edited by Andrei Bobrov on 27 May 2013
Accepted answer

after John's comment in Image Analyst's answer:

out = accumarray([x(:),y(:)],z(:),[10 10]); 


out = zeros(10);
out(sub2ind(size(out),x,y)) = z;


John on 27 May 2013

Thanks! it works now :)

Andrei Bobrov on 27 May 2013

Hi John! NOTE: Second part my answer (code after 'or') is the same as the Image Analyst' answer...

John on 27 May 2013

Now I get it, thanks for the clarification.

Andrei Bobrov
Answer by Image Analyst on 26 May 2013

Try this:

% Setup / initialization.
% Start out matrix as zeros.
m = zeros(20,10);
% Generate 100 random coordinates.
xy = int32(randi(10, 100, 2));
% Get matrix values for those x,y locations
z = randi(255, 100, 1); % 100 values.
% Now, do what the poster, John, wants to do.
% Assign the z values to the (x,y) coordinates at the corresponding row.
% E.g. m at (x(1), y(1)) will have a value of z(1).
% m at (x(2), y(2)) will have a value of z(2).  And so on.
indexes = sub2ind([20, 10], xy(:,1), xy(:,2))
m(indexes) = z


John on 27 May 2013

Thanks for your help, unfortunately it didn't work. Here's my data. x and y are the coordinates and z is the corresponding value for each coordinate.

x [4 7 5 9 3 5 5 2 1 1 ]

y [9 2 9 7 9 9 1 4 7 6 ]

z [1 0 1 1 1 0 1 0 1 0 ]

I wish to create a 10x10 matrix (since my xy coordinates are between 1 and 10). In this matrix, I want each coordinate, say for instance, the first xy coordinate (4,9) whose z value is 1 is shown as 1 in column 4 row 9 of the matrix.

Image Analyst on 27 May 2013

Of course it DOES work if you adapt it to a 10 by 10.

indexes = sub2ind([10, 10], x, y)
m(indexes) = z

When I did my example, I picked random numbers for x, y, and z, and random sizes. You were supposed to know that and be able to make the simple adaptations yourself. But anyway, andrei did it for you so you're all set now.

Image Analyst

Contact us