258 views (last 30 days)

%This is a program for calculating electric field for n number of charges

%where the source and field points are in cartesian coordinates.

%First, defining the proportionality constant

K=8.99*10^9;

%Taking the input for n no. of charges

n=input('Enter number of charges: ');

for i=1:n

q(i)=input('Enter the charge in coulombs: ');

end

%Taking the coordinates of the field point

disp('Enter the coordinates for the field point :');

xf=input('Enter x coordinate of the field point : ' );

yf=input('Enter y coordinate of the field point: ');

zf=input('Enter z coordinate of the field point: ');

%Taking the coordinates of n source points for n charges

disp('Enter the coordinates for the source point for the four charges :');

for m=1:n

x(m)=input('Enter x coordinate : ' );

y(m)=input('Enter y coordinate : ');

z(m)=input('Enter z coordinate : ');

%field point - source point for getting vector r

xi(m)=xf-x(m);

yi(m)=yf-y(m);

zi(m)=zf-z(m);

end

%Performing the summation portion of the formula

sum=0;

for m=1:n

mag(m)=(sqrt(xi(m)^2 + yi(m)^2 + zi(m)^2))^3;

sum=sum+q(m)*([xi(m),yi(m),zi(m)]/mag(m));

end

%Finally multiplying it by K

disp('The electric field intensity is :');

ef=K*sum;

ef

Andreas Bernatzky
on 16 Mar 2020

As darova already mentioned it is really annoying. You should think about a different user input.

But for visualizing I would suggest something like surf(), mesh().

Create a 2D matrix with the size of your [min,max] values for the cartesian xy-coordinates. Calculate the field intensity in each point. Than just use surf() or mesh() on your matrix. For every z-Coordinate i would create an extra 2D Matrix.

yourElectricField = rand(5,5); % create a random 2D matrix with the size of 5 in x and 5 in y

surf(yourElectricField); %simple visualization

Thats just my personal opinion of your problem because I do not know your application and neither I am a expert for electric fields but I think I get the problem.

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!
## 1 Comment

## Direct link to this comment

https://in.mathworks.com/matlabcentral/answers/511074-i-have-made-a-code-for-calculating-the-electric-field-intensity-for-n-charges-i-need-help-plotting#comment_810608

⋮## Direct link to this comment

https://in.mathworks.com/matlabcentral/answers/511074-i-have-made-a-code-for-calculating-the-electric-field-intensity-for-n-charges-i-need-help-plotting#comment_810608

Sign in to comment.