필터 지우기
필터 지우기

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

조회 수: 7 (최근 30일)
Rodrigo Ayala
Rodrigo Ayala 2021년 3월 8일
답변: Walter Roberson 2021년 3월 9일
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