# how to combine symbolics and if statement?

18 vues (au cours des 30 derniers jours)
Karthik Nimishakavi le 15 Oct 2016
Modifié(e) : Karan Gill le 17 Oct 2017
Hello, My function is like this
y=x+2 for 0<=x<=10
y = x^2 for 10<x<=500 and x belongs to 0,500.
so I tried like this
syms x
if x>=0 && x<=10
y=x+2
else y=x^2
end
but i am getting an error saying
"Conversion to logical from sym is not possible"
"Operands to the || and && operators must be convertible to logical scalar values".
##### 0 commentairesAfficher -2 commentaires plus anciensMasquer -2 commentaires plus anciens

Connectez-vous pour commenter.

### Réponse acceptée

Walter Roberson le 15 Oct 2016
You cannot use if together with symbolic expressions.
You should be considering using numeric expressions together with logical indexing. See though http://www.mathworks.com/matlabcentral/answers/301165-ode-suite-for-solving-switched-systems#comment_397941 for a discussion on hidden problems with one way of coding that.
You could also code the obscure
evalin(symengine, 'piecewise([0 <= x and x <= 10, x+2], [10 < x and x <= 500, x^2])')
but you will find that it probably will not be of any use to you.
##### 1 commentaireAfficher -1 commentaires plus anciensMasquer -1 commentaires plus anciens
Karthik Nimishakavi le 15 Oct 2016
thanks, I'll try that

Connectez-vous pour commenter.

### Plus de réponses (1)

Karan Gill le 20 Oct 2016
Modifié(e) : Karan Gill le 17 Oct 2017
Piecewise is available starting 16b: <http://www.mathworks.com/help/symbolic/piecewise.html>
In this case:
syms y(x)
y(x) = piecewise(0<=x<=10, x+2, 10<x<=500, x^2);
Now try
y(1)
ans =
3
>> y(12)
ans =
144
##### 1 commentaireAfficher -1 commentaires plus anciensMasquer -1 commentaires plus anciens
Walter Roberson le 20 Oct 2016
Thanks, Karan, I had missed seeing that.

Connectez-vous pour commenter.

### Catégories

En savoir plus sur Conversion Between Symbolic and Numeric dans Help Center et File Exchange

### Community Treasure Hunt

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

Start Hunting!

Translated by