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

19 次查看(过去 30 天)
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
Please, any tips/advice or help would be greatly appreciated! Thanks.

采纳的回答

Alex Mcaulley
Alex Mcaulley 2019-10-29
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 个评论
Daniel Tanner
Daniel Tanner 2019-10-29
Hi, thanks for replying so quickly!
So I have tried it this way and result in the error:
Index in position 1 is invalid. Array indices must be positive integers or logical values.
Error in Untitled4 (line 11)
R(i,j) = sqrt(i.^2+j.^2);
Which I am not sure what that means.
Alex Mcaulley
Alex Mcaulley 2019-10-29
编辑:Alex Mcaulley 2019-10-29
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);

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Contour Plots 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by