Need help with symbolic variables (if else statement)
Show older comments
if a > 10^-8
switch1 = b;
else
switch1 = 0;
end
i get the following error:
Conversion to logical from sym is not possible.
at line:
if a > 10^-8
I Need the above code to work with symbolic variables.
Accepted Answer
More Answers (1)
Adam Danz
on 13 Jul 2018
According to your comments, 'a' is a symbol symbolizing a scalar number. If that's the case, you can convert 'a' to numerical.
a = sym('3.14159');
a = double(a); % Convert to double
if a > 10^-8
...
else
...
end
If you prefer to keep 'a' in the sym class, use Walter's answer.
10 Comments
Walter Roberson
on 13 Jul 2018
If a could be converted to double then "if" would not have complained about it, unless perhaps in R2011a and earlier (I would need to check whether the earlier releases did the automatic conversion.)
With all current versions,
if sym(5) > 3
disp('yep');
else
disp('no');
end
will work fine.
The problem arises when you try to compare a symbolic expression that contains values that double() will not work with, such as if it contains an unresolved symbolic variable or if it contains an int() that is divergent, or a limit() that MATLAB cannot decide. For those cases, you need piecewise()
Walter Roberson
on 13 Jul 2018
Watch out for the definition of heaviside when the input argument is exactly 0. See sympref('HeavisideAtOrigin')
Note that if you are taking these symbolic equations and converting them for use with the numeric ode*() routines (such as by using odeFunction()) then you can have problems. The numeric routines such as ode45() require that the functions be twice differentiable, so they cannot handle discontinuities such as you are programming. When you use routines such as ode45(), you need to stop the integration at each discontinuity and then resume with a new ode*() call. If the discontinuity is time based, you can do that by using the tspan to integrate for a limited time, and then call again for the next time span. If the discontinuity is not time based, then you would need to program event functions for this purpose.
Akbar
on 14 Jul 2018
Walter Roberson
on 17 Jul 2018
Could you post the full code that calls amiwrap? I have downloaded the toolbox but it is easier to examine when there is a particular example to test with.
Walter Roberson
on 17 Jul 2018
Sorry, I only answer public questions.
Categories
Find more on Common Operations in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!