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

조회 수: 21 (최근 30일)
Daniel Tanner
Daniel Tanner 2019년 10월 29일
편집: Alex Mcaulley 2019년 10월 29일
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