%MMI361 Project2 Part2
%beam and displacement of swept steered array

clear all;
close all;
clc;

l=1;
c=344;
f=1500;
lambda=c./f;
k=2*pi*f/c;
b=-1/2:(1/4000):(1/2);
bpi=b*pi;
points = [0:1:90,90:-1:-90,-90:1:90,90:-1:-90,-90:1:0];   %the main lobe points to this direction in degrees

for i = 1:length(points);
    point = points(i);
    ks=2*pi*f/cs; 
    lambdas=2*pi./ks; 
    
    % Beam pattern
    for j=1:length(bpi)
        p0(j)=sin(pi*l*(sin(bpi(j))/lambda-1/lambdas))/(pi*l*(sin(bpi(j))/lambda-1/lambdas));
        p1(j)=sin(pi*l*((sin(bpi(j))/lambda-1/lambdas)+1))/(pi*l*(sin(bpi(j))/lambda-1/lambdas+1));
        p2(j)=sin(pi*l*((sin(bpi(j))/lambda-1/lambdas)-1))/(pi*l*(sin(bpi(j))/lambda-1/lambdas-1));
        p(j)=p0(j)+0.5*(p1(j)+p2(j));
    end
    subplot(121);
    polar(bpi,abs(p),'m-')
    title(['Beam pattern: f = ', num2str(f),' Hz, Angle: ', num2str(point), ' Degrees'])
    
    % Displacement pattern
    [X,Y] = meshgrid(0:0.05:5,-2.5:0.05:2.5); 
    R=sqrt((X.^2)+(Y.^2));
    sin_tn=Y./sqrt(X.^2+Y.^2);
    m=sin_tn/lambda;
    s=1./lambdas;
    u=m-s;
    q=(sin(pi*l*u)./(pi*l*u) + 0.5*sin(pi*l*(u+1))./(pi*l*(u+1)) + 0.5*sin(pi*l*(u-1))./(pi*l*(u-1))).*cos(k*R)./R;
    subplot(122), surf(X,Y,q+1), axis ([0 5 -2.5 2.5 -10 20])%q+1 is just a level adjustment for better color
    caxis([-5 5])
    title(['Displacement pattern: f = ', num2str(f),' Hz, Angle: ', num2str(point), ' Degrees'])
    view(60, 40)
    figure(gcf)
end
