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

20 ビュー (過去 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 Center および File ExchangeContour Plots についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by