Problem

Develop an M-file to determine polar coordinates as described in Prob. 3.6. However, rathe...

Develop an M-file to determine polar coordinates as described in Prob. 3.6. However, rather than designing the function to evaluate a single case, pass vectors of x and y. Have the function display the results as a table with columns for x, y, r, and θ. Test the program for the cases outlined in Prob. 3.6.

Step-by-Step Solution

Solution 1

Write the M-file and save it as polar2.m

Code:

function polar2(x, y)

r = sqrt(x .^ 2 + y .^ 2);

n = length(x);

for i = 1:n

if x(i) > 0

th(i) = atan(y(i) / x(i));

elseif x(i) < 0

if y(i) > 0

th(i) = atan(y(i) / x(i)) + pi;

elseif y(i) < 0

th(i) = atan(y(i) / x(i)) - pi;

else

th(i) = pi;

end

else

if y(i) > 0

th(i) = pi / 2;

elseif y(i) < 0

th(i) = -pi / 2;

else

th(i) = 0;

end

end

th(i) = th(i) * 180 / pi;

end

ou=[x;y;r;th];

fprintf('\n x y radius angle\n');

fprintf('%8.2f %8.2f %10.4f %10.4f\n',ou);

Output:

>> x=[1 1 0 -1 -1 -1 0 0 1];

>> y=[0 1 1 1 0 -1 0 -1 -1];

>> polar2(x,y)

x y radius angle

1.00 0.00 1.0000 0.0000

1.00 1.00 1.4142 45.0000

0.00 1.00 1.0000 90.0000

-1.00 1.00 1.4142 135.0000

-1.00 0.00 1.0000 180.0000

-1.00 -1.00 1.4142 -135.0000

0.00 0.00 0.0000 0.0000

0.00 -1.00 1.0000 -90.0000

1.00 -1.00 1.4142 -45.0000

>>

Add your Solution
Textbook Solutions and Answers Search
Solutions For Problems in Chapter 3