Please write out the code in Matlab! Create a user defined function that will co
ID: 3110020 • Letter: P
Question
Please write out the code in Matlab!
Create a user defined function that will convert a coordinate (x, y) in the Cartesian Coordinate System to a Polar coordinate (r, theta) where theta is in degrees, referenced positive counter clockwise from the x-axis. Use the function definition line function [r, th] = cart2polar(x, y) in your solution. Keep in mind that there are four quadrants in the Cartesian system and the traditional sine and cosine functions only provide the first quadrant value. Assume only scalar values will be sent to the function. function y = cart2polar(x) y = x; endExplanation / Answer
%%%% Function
function [ r , th] =cart2polar( x,y)
r=sqrt(x^2+y^2);
th=atan(y/x)*180/pi;
if (x<0 && y>0);
th= 180+th;
elseif (x<0 && y<0)
th=180+th;
elseif (x>0 && y<0)
th=360+th;
else
th=th;
end
end
%%%main programm
clc;
clear all;
close all;
[r,th]=cart2polar(1,1);
fprintf('cart2polar(1,1) is [r,th]=[%f, %f ] ',r,th);
[r,th]=cart2polar(-1,1);
fprintf('cart2polar(-1,1) is [r,th]=[%f, %f ] ',r,th);
[r,th]=cart2polar(-1,-1);
fprintf('cart2polar(-1,-1) is [r,th]=[%f, %f ] ',r,th);
[r,th]=cart2polar(1,-1);
fprintf('cart2polar(1,-1) is [r,th]=[%f, %f ] ',r,th);
Output :
cart2polar(1,1) is [r,th]=[1.414214, 45.000000 ]
cart2polar(-1,1) is [r,th]=[1.414214, 135.000000 ]
cart2polar(-1,-1) is [r,th]=[1.414214, 225.000000 ]
cart2polar(1,-1) is [r,th]=[1.414214, 315.000000 ]