How to convert a string to a symbol ?
26 views (last 30 days)
Show older comments
Hello guys ,
I just wanted to convert this string :
'x & 1'
to a symbol ,i tried to use sym() function ,which seemed not to work ,obviously ,it doesn't seem to symbolize some characters ,like ampersands ,asterisks ,arithmetic operators , etc...
So any help how can i convert the above string to a symbol ?!
Much Regards
0 Comments
Accepted Answer
Ahmed A. Selman
on 26 Mar 2013
@Jacky (the actual expression is : (x>=1 & x<9)). This is the question!
This is a logical comparison statement. The meaning of (&) - Logical AND in Matlab in comparisons is
&&
So try this
if (x>=1 && x<9)
y=2*x+12;% here is what to do when the condition is fulfilled
else
y=0;% here is what to do when the condition is not fulfilled
end
There is a (symbolic) programming tools in Matlab, initialized with
sym
or
syms
e.g.,
syms x y z
whos
Name Size Bytes Class Attributes
x 1x1 58 sym
y 1x1 58 sym
z 1x1 58 sym
the same output we''ll get when using
syms ('x', 'y','z')
and x, y, z (or any other argument) must be variables name. Variables names must not contain special characters such as '&'.
After we defined the syms above, we can try this:
f=(cos(x)+sin(y))/z
fPrime=diff(f,x)
fPrime =
-sin(x)/z
where fPrime is the differentiation of f with respect to the variable x... and so on.
Converting (string to symbol in Matlab) is still not clear to me.
Regards :)
1 Comment
Walter Roberson
on 26 Mar 2013
Both & and && are logical comparisons in MATLAB. && is "shortcut and" which only works on scalars and does not evaluate the right-hand side if it already knows the answer from the left-hand side.
The difficulty being had is what I described above: the MuPAD, the symbolic language, does not use & or && at all: it uses "and"
More Answers (3)
Ahmed A. Selman
on 25 Mar 2013
sym and syms are used to declare symbolic variables, see:
Please specify your idea about (converting a string to symbol in Matlab), do you mean (string to a variable), as in
x=1
y=-90
if so, Matlab variables must not contain special characters as (~!@#$%^&*)..etc. Or you mean text properties in figures? Then Refer to http://www.mathworks.com/help/matlab/ref/text_props.html.
If it was translating a string into an expression, see the functions
regexptranslate
regexp
5 Comments
Walter Roberson
on 25 Mar 2013
When you use
sym('x & 1')
what result are you seeing?
Question: would x&1 be the formula or the limit? Were you meaning
sym('x < 1')
?
Walter Roberson
on 25 Mar 2013
MuPAD does not use & for logical conjugation. See http://www.mathworks.com/help/symbolic/logical-operations-1.html
0 Comments
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!