# How to find the position of points in a coordinate system?

13 views (last 30 days)
Daniel Tanner on 29 Oct 2019
Edited: Alex Mcaulley on 29 Oct 2019
I am new to MatLab and still learning how to use 'for' loops correctly, as I may not even need to use one here.
I am trying to set up a coordinate system which will then cycle through every point and find the distance. I have coded the coordinate system like so:
x_step = 0.01;
z_step = 0.02;
Z = (-5:z_step:5);
X = (0:x_step:5);
which leaves me with two vectors, both with dimensions of 1-by-501.
Now the equation I am using to calculate the response at some point in the coordinate space is:
How would I write code which tells me the distance at each point?
I have had a go at writing a simple for loop which just outputs one value which I assume is the last. Here is the code:
for i = X
for j = Z
R = sqrt(i.^2+j.^2);
end
end

Alex Mcaulley on 29 Oct 2019
Using for loops:
R = zeros(numel(X),numel(Z));
for i = X
for j = Z
R(i,j) = sqrt(i.^2+j.^2);
end
end
##### 2 CommentsShowHide 1 older comment
Alex Mcaulley on 29 Oct 2019
Then, the solution should be:
x_step = 0.01;
z_step = 0.02;
Z = (-5:z_step:5);
X = (0:x_step:5);
R = zeros(numel(X),numel(Z));
for i = 1:numel(X)
for j = 1:numel(Z)
R(i,j) = sqrt(X(i).^2+Z(j).^2);
end
end
Or a better solution:
x_step = 0.01;
z_step = 0.02;
Z = (-5:z_step:5);
X = (0:x_step:5);
[Z,X] = meshgrid(Z,X);
R = sqrt(X.^2+Z.^2);
And still better
x_step = 0.01;
z_step = 0.02;
Z = (-5:z_step:5);
X = (0:x_step:5);
R = sqrt(Z.^2+X'.^2);
{"found_math": false, "script_math_tex": 0, "script_math_asciimath": 0, "math_annotations": 0, "math_alttext": 0, "mathml": 0, "mathjax_tag": 0, "mathjax_inline_tex": 0, "mathjax_display_tex": 0, "mathjax_asciimath": 0, "img_math": 0, "codecogs_latex": 0, "wp_latex": 0, "mimetex.cgi": 0, "/images/math/codecogs": 0, "mathtex.cgi": 0, "katex": 0, "math-container": 0, "wp-katex-eq": 0, "align": 0, "equation": 0, "x-ck12": 0, "texerror": 0}