MATLAB: There are many errors I cannot spot in this script. Can someone help please

basic functionMATLAB

This is what I am working with and I absolutely cannot get it to work.
function [r,theta,phi] = EGA118_M2_Q3s (x,y,z)
%%
%% This function returns the spherical polar coordinates (r, theta, phi)
%% that correspond to the input Cartesian coordinates (x, y, z).
%% theta (azimuthal angle) and phi (polar angle) are expressed in degrees.
if nargin == 0
r = 0;
theta = atan2(y,x);
phi = 0;
elseif nargin == 1
r = x;
theta = atan2(y,x);
phi = 0;
elseif nargin == 2
r = sqrt(x^2+y^2);
theta = atan2(y,x);
phi = 0;
else
r = sqrt(x^2+y^2);
theta = atan2d(y,x);
phi = atan2(z,r);
end
end

Best Answer

Hi Gabriel,
Yes. You are right, there are several errors.
  1. In the if condition of nargin == 0, the variable theta should be updated to 0. Rather than the formula
  2. In the elseif condition of nargin == 1, the variable theta should be updated to 0. Rather than the formula
  3. In the elseif condition of nargin == 2, the variable theta should be updated with atan2d rather than atan2
  4. In the last else condition, the variable phi must be updated with atan2d rather than atan2
To provide some insights of what the changes are, nargin stands for number of input arguments. The maximum number of input arguments are 3. Here is the documentation for nargin function https://in.mathworks.com/help/matlab/ref/nargin.html
The next change is update in atan2 function with atan2d. atan2d returns the output in degrees which is asked for in the comments, whereas atan2 returns the output in radians. Here are the documentation pages of atan and atan2d functions.
The consolidated code is here
function [r,theta,phi] = EGA118_M2_Q3s (x,y,z)
%%
%% This function returns the spherical polar coordinates (r, theta, phi)
%% that correspond to the input Cartesian coordinates (x, y, z).
%% theta (azimuthal angle) and phi (polar angle) are expressed in degrees.
if nargin == 0
r = 0;
theta = 0; % Since nargin == 0, there are no inputs, so output is 0
phi = 0;
elseif nargin == 1
r = x;
theta = 0; % atan2d(0/x); % Since nargin == 1, the input y is not defined, implies set to 0
phi = 0;
elseif nargin == 2
r = sqrt(x^2+y^2);
theta = atan2d(y,x); % Replace it with degrees

phi = 0;
else
r = sqrt(x^2+y^2);
theta = atan2d(y,x);
phi = atan2d(z,r); % Replace it with degrees
end
end
Hope this helps.
Regards,
Sriram