[edit: I submitted the answer prematurely.]
Code 2 runs without error. Why do you think code 2 needs fixing?
AF(m,p)=sum(exp(-1i*(N/2)*sin(theta(m))*(cos(phi(p)-phi_n))));
x(m,p)=abs(AF(m,p))*sin(theta(m))*cos(phi(p));
y(m,p)=abs(AF(m,p))*sin(theta(m))*sin(phi(p));
z(m,p)=abs(AF(m,p))*cos(theta(m));
fprintf('M=%d, P=%d.\n',M,P);
xlabel('p'); ylabel('m'); zlabel('x'); grid on
xlabel('x'); ylabel('y'); zlabel('z');
title('abs(AF)'); axis equal; grid on
You can delete P1 and M1, since they are not used. The rest of the code works. If you are unhappy with the output of code 2, please explain why.
In code 1, x0 is a row vector with M=4 columns. Each element of x0 is computed by adding up P=2 complex components. y0 and z0 are similar.
In code 2, AF(m,p) is a 10x37 complex array. The values of AF() span a hemisphere, at 10 degree increments, from -180 to +180 in azimuth, and from 0 to 90 in elevation. Arrays x,y,z are the x,y,z, components of abs(AF), by a standard spherical-to-Cartesian coordinate transformation, assuming
points along the z-axis, and
points along the x-y plane. I have added a plot of x(m,p) and a plot of the abs(AF) surface.