Division by zero error when evaluating symbolic expression in MATLAB

2.2k Views Asked by At
clear all

syms s w 

G = 1/((s)*(s+1)*(s+2)); %transfer function
G_w = subs(G,s,j*w); 
W= [-100:0.01:100]; %[min_range:step size:max_range]
nyq = eval(subs(G_w,w,W)); 

x = real(nyq)
y = imag(nyq)

plot(x,y)

I can't seem to run this code and it keeps displaying error in line 100++ where I've only less than 20 lines.

Error using symengine (line 59)
Division by zero.
Error in sym/subs>mupadsubs (line 139)
G = mupadmex('symobj::fullsubs',F.s,X2,Y2);
Error in sym/subs (line 124)
    G = mupadsubs(F,X,Y);
Error in nyquist2 (line 8)
nyq = eval(subs(G_w,w,W)); %replace W with w in equation G_w

This are the errors shown, any expert could help me in this ?

2

There are 2 best solutions below

2
On BEST ANSWER

The error is because you are computing G_w using the array W and this array contains the value 0 resulting in a division by zero and therefore the error.

Error using symengine (line 59)
Division by zero.

What you can do to get around this, is to replace the 0 in W with eps.

% Replace zeros with epsilon
W(W == 0) = eps;

nyq = eval(subs(G_w,w,W)); 

x = real(nyq)
y = imag(nyq)

plot(x,y)

As a side-note, the error isn't complaining about an issue with line 100+ of your code, but rather the stack trace is stating that the error actually originated from within a function that you're calling

The stack trace is ordered from where the error occured to the code that you called to create it

Error using symengine (line 59)             <--- WHERE THE ERROR HAPPENED
Division by zero.                           <--- THIS IS THE ERROR MESSAGE

Error in sym/subs>mupadsubs (line 139)      <--- THIS FUNCTION CALLED symengine
G = mupadmex('symobj::fullsubs',F.s,X2,Y2); <--- THIS IS THE LINE THAT CALLED symengine

Error in sym/subs (line 124)                <--- THIS FUNCTION CALLED mupadsubs
G = mupadsubs(F,X,Y);                       <--- THIS IS THE LINE THAT CALLED mupadsubs

Error in nyquist2 (line 8)                  <--- THIS FUNCTION (YOURS) CALLED subs
nyq = eval(subs(G_w,w,W))                   <--- THIS IS THE LINE THAT CALLED subs
0
On

@Suever's answer is definitely a better solution in this case where a large number of values must be computed, but another solution if you are looking to evaluate the function at only one value (0) and want to avoid the division-by-zero error, you can do this:

>> limit(G_w,w,0)
 
ans =
 
NaN

This is quite computationally intensive though, so it's only worth using when you expect a division-by-zero (e.g. at w = 0).