%
%   Book: MATLAB-Based Electromagnetics (Pearson Prentice Hall)
%   Author: Branislav M. Notaros
%   Instructor Resources
%   (c) 2011
%
%   This MATLAB code or any part of it may be used only for 
%   educational purposes associated with the book
%
%
%


%   Fields  due to line charges of finite and infinite lengths


close all;
clear all;
EPS0 = 8.854*10^(-12);   

L = input('Enter the length of line in cm: ');
L = L * 10^(-2);
dens = input('Enter the line charge in nC/m: ');
dens = dens * 10^(-9);
dD = 0.005*L;
D0 = 0.1*L;
D1 = 2*L;
D = D0:dD:D1;
k = D/L;
midpoint = L / 2;
theta2 = atan( midpoint./D);
theta1 = -theta2;

%Electric Field

EFinite = (dens./(4*pi*EPS0*D)).*(sin(theta2)-sin(theta1));

%Electric Field due to infinite line charge

EInfinite = dens./(2*pi*EPS0*D);

%relative error
Error = abs(EFinite - EInfinite)*100./EFinite;  
ErrorMax = 5;  

Emax = max(EInfinite);
[delta,n] = min(abs(Error - ErrorMax));
kmax = (D0+(n-1)*dD)/L;
disp('The Error of 5% is at D/L = kmax =');
disp(kmax);

figure(1);
plot(k,EFinite,'r',k,EInfinite,'m--');
line([kmax kmax],[0 Emax]);
legend('finite','infinite');
title('Comparison of E-fields due to finite and infinite lines of charge');
text(kmax,Emax*0.9,['k = kmax = ',num2str(kmax)]);
xlabel('k = D/L');
ylabel('E[V/m]');




