Wednesday, October 8, 2014

Native Function for Parsing String to Math Expression

My last post was about parsing strings to math functions, like:

parsingStr2Arithmetics("2+2")
 ans  =

    4.  

But, Scilab has a native function that evaluates strings:

evstr()

There are some examples using this function:

-->evstr("1")
 ans  =

    1.

-->evstr("1+1")
 ans  =

    2.

-->evstr("2*(1+8)/3")
 ans  =

    6.

-->evstr("2*(1+1)")
 ans  =

    4.

-->evstr("2*(1+1) a")
%val=[2*(1+1) a;
                !--error 4
Variável indefinida: a
in  execstr instruction    called by :
at line      35 of function evstr called by :
evstr("2*(1+1) a")


Take a look that last example ahs failed, it happened because the argument "2*(1+1) a" does not mean a valid expression.

Thus, there is a optimized way to do this task and work with strings which mean math expressions.

Another useful use for this function is to use it for running another functions, for example:

-->evstr("exp(1)")
 ans  =

    2.7182818

-->evstr("sin(%pi/2)")
 ans  =

    1.

-->evstr("zeros(5, 5)")
 ans  =

    0.    0.    0.    0.    0.
    0.    0.    0.    0.    0.
    0.    0.    0.    0.    0.
    0.    0.    0.    0.    0.
    0.    0.    0.    0.    0.

To put a string in the argument, there is needed to use an inside single quote ', like this:

-->"'"my string'""
 ans  =

 "my string"  


So, the function evstr() may evaluate strings with other strings inside, like this:

-->evstr("'"my'"+ '" string'"")
 ans  =

 my string  

-->evstr("length('"test'")")
 ans  =

    4.

-->evstr("strsplit('"this is a string inside'", '" '")")
 ans  =

!this    !
!        !
!is      !
!        !
!a       !
!        !
!string  !
!        !
!inside  !

Think out of the box, strings may mean math and any other functions or sentence!

2 comments:

ASTA BLACK said...

ada yang penasaran dengan sabung ayam toraja

Blogger said...

Water Hack Burns 2 lb of Fat OVERNIGHT

More than 160 000 men and women are using a simple and SECRET "water hack" to lose 1-2 lbs every night while they sleep.

It is very simple and it works with everybody.

Here's how you can do it yourself:

1) Grab a glass and fill it half the way

2) And now do this proven HACK

so you'll become 1-2 lbs skinnier in the morning!