How to find the position of points in a coordinate system?
20 次查看(过去 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.
0 个评论
采纳的回答
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 个评论
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 Exchange 中查找有关 Contour Plots 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!