I need to write a program that uses Cartesian coordinates to find the position o
ID: 2995409 • Letter: I
Question
I need to write a program that uses Cartesian coordinates to find the position of a point in terms of polar coordinates, and then display in a chart the values for 9 sets of x&y. When i run my program, angle = 90 instead of a column vector! what am i doing wrong here! help plz!!
here is my program
x=[2,2,0,-3,-2,-1,0,0,2]';
y=[0,1,3,1,0,-2,0,-2,2]';
n=length(x);
radius=sqrt((x.^2+y.^2));
angle=((atan(y/x)*(180/pi)));
for i = 1:n
if x(i)<0
if y(i)>0
angle=atan(y/x)*(180/pi)+180;
elseif y(i)<0
angle=atan(y/x)*(180/pi)-180;
else
angle=180;
end
end
if x(i)==0
if y(i)>0
angle=180/2;
elseif y(i)<0
angle=-180/2;
else
angle=0;
end
end
end
z=[x';y';radius'; angle'];
fprintf('x y radius angle ');
fprintf('%d %3d %7.2f %8.2f ',z);
Explanation / Answer
You need to use angle (i) instead of angle in the for loop. The corrected program is as follow.
clc
x=[2,2,0,-3,-2,-1,0,0,2]';
y=[0,1,3,1,0,-2,0,-2,2]';
n=length(x);
radius=sqrt((x.^2+y.^2));
angle=((atan(y./x)*(180/pi)));
for i = 1:n
if x(i)<0
if y(i)>0
angle(i)= atan(y(i)/x(i))*(180/pi)+180;
elseif y(i)<0
angle(i)=atan(y(i)/x(i))*(180/pi)-180;
else
angle(i)=180;
end
end
if x(i)==0
if y(i)>0
angle(i)=180/2;
elseif y(i)<0
angle(i)=-180/2;
else
angle(i)=0;
end
end
end
z=[x y radius angle];
fprintf(' x y radius angle ');
for i = 1:n
fprintf('%3d %3d %7.2f %8.2f ',z(i,:));
end