How can i handle division by zero inside the symsum function?

5 次查看(过去 30 天)
I'm trying to model electric potential energy of 3 proton arranged in A(-1,0), B(0,0), C(0,1), graphically is(the next plot was made manually in geogebra 3d):
Asumming k=1, q1=1, q2=2 , mathematically can been described as:
The thing is that i want to generalize this into a summation function in matlab for n charges separated in the x-axis by a distance of 1 unit, mathematically it will be:
So i try the next code in matlab going form a=-1 to b=1:
[x,y]=meshgrid(-10:1:10);
syms k;
z=symsum((1./((x-k).^2+y.^2)),k,-1,1);
%Converts sym data type from the variable z to double data type for 3d plotting
doubleN = double(z);
surf(doubleN)
Next, it appears me the next code:

采纳的回答

Matt J
Matt J 2021-3-8
编辑:Matt J 2021-3-8
Why do things symbolically at all?
[x,y,k]=meshgrid(-10:1:10,-10:1:10, -1:+1);
z= sum( 1./((x-k).^2+y.^2) , 3);
surf(x(:,:,1),y(:,:,1),z);

更多回答(1 个)

Walter Roberson
Walter Roberson 2021-3-9
z=symsum((1./((x-k).^2+y.^2)),k,-1,1);
That is not worth doing with symsum. It is only 3 terms; just write them out, or use a vectorized calculation.
For example
dim = max(ndims(x),ndims(y)) + 1;
k = reshape(-1:1:1, 1, 1, dim);
z = sum(1./((x-k).^2+y.^2), dim);
In the case that y == 0 then Yes you get a division by 0 at each place one of the x exactly equal one of the k values -- but those will not stop the calculation (you will get +/- inf or nan depending on the exact expression.)

类别

Help CenterFile Exchange 中查找有关 Calculus 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by