Problem

A vector is a mathematical quantity that has both magnitude and direction. A 2-dimensional vector can be represented as a displacement along $x$ and $y$ axes in rectangular (Cartesian) coordinates or, by a distance $r$ and an angle $\phi$ in polar coordinates,

The conversion rule between the Cartesian and Polar representations of a vector.

The relationships between the Cartesian $(x,y)$ and polar $(r,\phi)$ coordinates are given by the following equations,

\[\begin{align*} x &= r\cos(\phi) \\ y &= r\sin(\phi) \\ r &= \sqrt{x^2 + y^2} \\ \end{align*}\]

Write a MATLAB function getPolar(inputCartesianStruct) that takes a structure inputCartesianStruct as input, that has two components x and y. Then on output, it returns another structure that has to components r and phi. Write another function getCart(inputPolarStruct) that does the inverse of getPolar(inputCartesianStruct). Make sure that both functions are robust to wrong input structures by checking whether the input structures have the required fields: x and y, or r and phi. You can do so by using MATLAB’s builtin function isfield().

Solution

MATLAB

Here is an example implementation of getPolar.m and getCart.m.

Comments