%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% HW 1, Problem 1.2 solution key
% Carlos J. Cela, Jan 2012
%
% Calculates and plots E field distribution in a 2D region due to the 
% presence of point electrical charges.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
clear all

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% First, calculate E field
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% Define region size
xmin = -1;
xmax = 1;
ymin = -1;
ymax = 1;


% Scale to 

% Initialize arrays to store E field vector components. The
% region will be divided in a number of points per axis for plotting.
Ex(1:51,1:51) = 0;
Ey(1:51,1:51) = 0; 


 
 
% Now iterate in the region of interest, dividing it in
% discrete points, to be able to plot
x = 0;
for i = xmin:(xmax-xmin)/50:xmax
  x = x+1;
  y = 0;
  for j = ymin:(ymax-ymin)/50:ymax
    y = y+1;   

    % Calculate Ex and Ey
    Ex(y,x) = sin(pi/2*j);
    Ey(y,x) = -sin(pi/2*i);

  end
end



%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Now, plot
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% Calculate and plot E field magnitude
figure(1);
imagesc(flipud(rot90(sqrt(Ex.^2+Ey.^2))));
colormap hot
grid on

% Flip Y-axis of image (by default this 
% type of plot is upside-down)
set(gca,'YDir','normal');

% Set tick marks on axes
set(gca,'XTick',[1 12.5 25 37.5 50]);
set(gca,'XTickLabel','-1|-0.5|0|0.5|1');
set(gca,'YTick',[1 12.5 25 37.5 50]);
set(gca,'YTickLabel','-1|-0.5|0|0.5|1');

% Add title and units, label axes
title('Electric field magnitude [V/m] and direction at each point', 'fontsize', 14);
xlabel('X position [m]', 'fontsize', 14);
ylabel('Y position [m]', 'fontsize', 14);

% Hold plot to overlap quiver on top
hold on 

% Add color bar scale for reference
colorbar

% Overlap E field vectors, scaling arrows by a factor
% of 2 so the direction can be seen clearly.
h = quiver(Ex, Ey);
set(h, 'LineWidth',1,'Color' , [.5 .5 .8]);
%axes([1 51 1 51]);
hold off




