evaluating strings

  • Permalink
  • submit to reddit
  • Email
  • Follow


Hello,

I would really appreciate any help with the problem I am currently
experiencing with the eval function.

s1='myif(plus(1,2),times(3,4))';
eval(s1);

When I do eval(s1) it executes plus(1,2) then times(3,4) then myif.
This is not acceptable since both plus and times are executed when
only one should be.

I have tried using function handles like this:

s2=@myif(@plus(1,2),@times(3,4));
eval(s2);

This works better however MATLAB executes either plus(1,2) or
times(3,4) and then myif. It executes the nested function first which
is also unacceptable.

I know this works perfectly:

s3='myif(''plus(''1'',''2'')'',''times(''3'',''4'')'')';
eval(s3);

It executes myif and then either plus(1,2) or times(3,4), depending
on the myif test.

So, what I would like to know is this, is there a way to go from s1
to s3 automatically?

s1='myif(plus(1,2),times(3,4))';
s3='myif(''plus(''1'',''2'')'',''times(''3'',''4'')'')';

I have tried to write a program using the brackets to indicate how
many quotation marks to wrap each function in but it is a very messy
solution. I have used strtok and strcat etc. but I have problems when
several brackets (delimiters) are touching each another.

If anyone out there can think of a solution to my problem (or the
larger eval issue) I would be extremely grateful.

Thank you so much in advance for your help.

Matt.

free_wombat@hotmail.com
0
Reply free_wombat (13) 7/20/2006 12:40:59 AM

See related articles to this posting


In article <ef3c24f.-1@webcrossing.raydaftYaTP>,
 "Matt C" <free_wombat@hotmail.com> wrote:

> Hello,
> 
> I would really appreciate any help with the problem I am currently
> experiencing with the eval function.
> 
> s1='myif(plus(1,2),times(3,4))';
> eval(s1);
> 
> When I do eval(s1) it executes plus(1,2) then times(3,4) then myif.
> This is not acceptable since both plus and times are executed when
> only one should be.
> 
> I have tried using function handles like this:
> 
> s2=@myif(@plus(1,2),@times(3,4));
> eval(s2);
> 
> This works better however MATLAB executes either plus(1,2) or
> times(3,4) and then myif. It executes the nested function first which
> is also unacceptable.
> 
> I know this works perfectly:
> 
> s3='myif(''plus(''1'',''2'')'',''times(''3'',''4'')'')';
> eval(s3);
> 
> It executes myif and then either plus(1,2) or times(3,4), depending
> on the myif test.
> 
> So, what I would like to know is this, is there a way to go from s1
> to s3 automatically?
> 
> s1='myif(plus(1,2),times(3,4))';
> s3='myif(''plus(''1'',''2'')'',''times(''3'',''4'')'')';
> 
> I have tried to write a program using the brackets to indicate how
> many quotation marks to wrap each function in but it is a very messy
> solution. I have used strtok and strcat etc. but I have problems when
> several brackets (delimiters) are touching each another.
> 
> If anyone out there can think of a solution to my problem (or the
> larger eval issue) I would be extremely grateful.
> 
> Thank you so much in advance for your help.
> 
> Matt.
> 
> free_wombat@hotmail.com

This is one of the most bizarre questions I have seen.  Congratulations.

I have no idea what you're trying to do, but here are some observations.

1)  We have no idea what the function myif is.  Perhaps we don't need to 
know, but knowing helps put the question into context.

2)  How do you know when only one or the other argument is evaluated?

3)  s3 evaluates to

  >> s3='myif(''plus(''1'',''2'')'',''times(''3'',''4'')'')' 
  s3 =
  myif('plus('1','2')','times('3','4')')


  plus('1','2') is not at all the same as plus(1,2).

4)  In the s1 example you seem surprised that both arguments are 
evaluated before they are passed into myif, but no other behavior is 
possible.  In your other examples you apparently defer execution by 
passing in a string instead of a value.  Why, I don't know.

5)  Since I don't know what myif is let's pretend that it's

  if A || B
    ...
  end

MATLAB uses "short_circuit" operators in this case so if you just wrote

  if plus(1,2) || times(3,4)

you should get the behavior you desire.

-- 
Doug Schwarz
dmschwarz&ieee,org
Make obvious changes to get real email address.
0
Reply see9548 (1248) 7/20/2006 1:05:26 AM

Doug Schwarz wrote:
>
>
> In article <ef3c24f.-1@webcrossing.raydaftYaTP>,
> "Matt C" <free_wombat@hotmail.com> wrote:
>
>> Hello,
>>
>> I would really appreciate any help with the problem I am
> currently
>> experiencing with the eval function.
>>
>> s1='myif(plus(1,2),times(3,4))';
>> eval(s1);
>>
>> When I do eval(s1) it executes plus(1,2) then times(3,4) then
> myif.
>> This is not acceptable since both plus and times are executed
> when
>> only one should be.
>>
>> I have tried using function handles like this:
>>
>> s2=@myif(@plus(1,2),@times(3,4));
>> eval(s2);
>>
>> This works better however MATLAB executes either plus(1,2) or
>> times(3,4) and then myif. It executes the nested function first
> which
>> is also unacceptable.
>>
>> I know this works perfectly:
>>
>> s3='myif(''plus(''1'',''2'')'',''times(''3'',''4'')'')';
>> eval(s3);
>>
>> It executes myif and then either plus(1,2) or times(3,4),
> depending
>> on the myif test.
>>
>> So, what I would like to know is this, is there a way to go
from
> s1
>> to s3 automatically?
>>
>> s1='myif(plus(1,2),times(3,4))';
>> s3='myif(''plus(''1'',''2'')'',''times(''3'',''4'')'')';
>>
>> I have tried to write a program using the brackets to indicate
> how
>> many quotation marks to wrap each function in but it is a very
> messy
>> solution. I have used strtok and strcat etc. but I have
problems
> when
>> several brackets (delimiters) are touching each another.
>>
>> If anyone out there can think of a solution to my problem (or
the
>> larger eval issue) I would be extremely grateful.
>>
>> Thank you so much in advance for your help.
>>
>> Matt.
>>
>> free_wombat@hotmail.com
>
> This is one of the most bizarre questions I have seen.
> Congratulations.
>
> I have no idea what you're trying to do, but here are some
> observations.
>
> 1) We have no idea what the function myif is. Perhaps we don't
> need to
> know, but knowing helps put the question into context.
>
> 2) How do you know when only one or the other argument is
> evaluated?
>
> 3) s3 evaluates to
>
> >> s3='myif(''plus(''1'',''2'')'',''times(''3'',''4'')'')'
> s3 =
> myif('plus('1','2')','times('3','4')')
>
>
> plus('1','2') is not at all the same as plus(1,2).
>
> 4) In the s1 example you seem surprised that both arguments are
> evaluated before they are passed into myif, but no other behavior
> is
> possible. In your other examples you apparently defer execution by
>
> passing in a string instead of a value. Why, I don't know.
>
> 5) Since I don't know what myif is let's pretend that it's
>
> if A || B
> ...
> end
>
> MATLAB uses "short_circuit" operators in this case so if you just
> wrote
>
> if plus(1,2) || times(3,4)
>
> you should get the behavior you desire.
>
> --
> Doug Schwarz
> dmschwarz&ieee,org
> Make obvious changes to get real email address.
>
  

Hello,

I would really appreciate any help with the problem I am currently
experiencing with the eval function.

s1='myif(plus(1,2),times(3,4))';
eval(s1);

When I do eval(s1) it executes plus(1,2) then times(3,4) then myif.
This is not acceptable since both plus and times are executed when
only one should be.

I have tried using function handles like this:

s2=@myif(@plus(1,2),@times(3,4));
eval(s2);

This works better however MATLAB executes either plus(1,2) or
times(3,4) and then myif. It executes the nested function first which
is also unacceptable.

I know this works perfectly:

s3='myif(''plus(''1'',''2'')'',''times(''3'',''4'')'')';
eval(s3);

It executes myif and then either plus(1,2) or times(3,4), depending
on the myif test.

So, what I would like to know is this, is there a way to go from s1
to s3 automatically?

s1='myif(plus(1,2),times(3,4))';
s3='myif(''plus(''1'',''2'')'',''times(''3'',''4'')'')';

I have tried to write a program using the brackets to indicate how
many quotation marks to wrap each function in but it is a very messy
solution. I have used strtok and strcat etc. but I have problems when
several brackets (delimiters) are touching each another.

If anyone out there can think of a solution to my problem (or the
larger eval issue) I would be extremely grateful.

Thank you so much in advance for your help.

Matt.

Thank you very much to those people who have looked at my problem and
especially to Doug Schwarz for replying.

I apologise if the way I originally presented my problem was not
clear. I guess the short version was too simplified so here�s the
long one. Although I do admit to making one error in my first post in
that s3 should have been written as

'myif(''plus(''''1'''',''''2'''')'',''times(''''3'''', ''''4'''')'')'


rather than

'myif(''plus(''1'',''2'')'',''times(''3'',''4'')'')'

as Doug realised.

This question has to do with the MATLAB genetic programming toolbox
written by Sara Silva which is available open source from <http://gplab.sourceforge.net/index.html>.



I believe it currently has one major unresolved problem and it
involves the eval function.

The GP program generates a population of random programs
(�individuals�) to solve problems. These generated programs are
represented as �trees� which are stored in nested structs. The
algorithm needs to evaluate each program to determine which ones work
the best.

Currently, programs are evaluated by first converting the tree struct
into a single layered string. In the artificial ant problem for
example, a program might look like this

string = 'antif(antif(antmove,antright),antleft)'

GPLAB then simply does eval(string) to evaluate the programs.
However, this does not work correctly (see my example programs at the
end).

About a year ago some French researchers using GPLAB wrote a program
to convert the tree structure into the strings with levels which
GPLAB could then evaluate correctly like this:

string = ' antif(''antif(''''antmove'''', ''''antright'''') '',
''antleft'') '

Unfortunately the toolbox is very large and making this change
affects many other programs.

It would be much simpler to have a new program that just converts
this

string = 'antif(antif(antmove,antright),antleft)'

to this

string = ' antif(''antif(''''antmove'''', ''''antright'''') '',
''antleft'') '

whenever an individual needs to be evaluated.

So there you have it. If anyone can think of an easy way to do this,
that would be great.

If you want to see how the eval function (mis)behaves then try out
each case of the following evalif program.

Thanks.

%evalif
 
clear all
clc
 
global x switchvar
x=0;
 
fprintf('\neval if')
fprintf('\n-----------------------\n')
 
switchvar='1';
 
switch switchvar
  
    case '1' % does NOT evaluate correctly
        iffunction(acttrue,actfalse);
    
    case '2' % does NOT evaluate correctly
        str='iffunction(acttrue,actfalse)';
        ans=eval(str);
        
    case '3' % does evaluate correctly
        iffunction(@acttrue,@actfalse);
        
    case '4' % but this does NOT evaluate correctly
        iffunction(iffunction(@acttrue,@actfalse),@actfalse);
        
    case '5' % does evaluate correctly
        str='iffunction(''acttrue'',''actfalse'')';
        ans=eval(str);
   
end
 
fprintf('\n-----------------------\n')
fprintf('\nfinal result: x = %d',x)
fprintf('\ncorrect result: x = 1\n')
 

function x=iffunction(a,b)
 
global x switchvar
 
fprintf('\nif function\n')
 
switch switchvar
    
    case '1' % if passing one string
        if 1
            a;
        else
            b;
        end
        
    case '2' % if calling functions directly
        if 1
            a;
        else
            b;
        end
        
    case '3' % if passing function handles
        if 1
            feval(a);
        else
            feval(b);
        end
        
    case '4' % if passing function handles
        if 1
            feval(a);
        else
            feval(b);
        end
        
    case '5' % if passing multiple strings
        if 1
            ans=eval(a);
        else
            ans=eval(b);
        end
 
end

function x=action1
 
global x
 
x=x+1;
 
fprintf('\nact true: x = %d\n',x)
 

function x=action2
 
global x
 
x=x+2;
 
fprintf('\nact false: x = %d\n',x)
0
Reply free_wombat (13) 7/20/2006 3:09:50 AM
comp.soft-sys.matlab 205344 articles. 554 followers. Post

2 Replies
116 Views

Similar Articles

[PageSpeed] 34


  • Permalink
  • submit to reddit
  • Email
  • Follow


Reply:

Similar Artilces:

paste a string as a string without evaluating contents
I am pasting data from Excel. In a long list of numbers/letters, I have the string: 1E4. I paste this into a cell array using the variable editor and "paste excel data", and what I get is 10000 because this got interpreted as scientific notation. Caused major headache and lost a lot of time. Is there a way to ensure that things get pasted as strings? I tried pre-defining the array as a cell (b=cell(11000,1)) but that did not prevent the problem. Is there a way to ensure that something is pasted as a string? Thanks! ...

string A = string A + string B (adding strings)
Hi, how can I perform the operation of adding string to string. string_A = string_A + string_B In particular I have to do: handles.hsl_current_string{1}(hsl_current_value{1}, :) = [handles.hsl_current_string{1}(hsl_current_value{1}, :), ' ' z1_value, ' ' z2_value, ' ' z_value] where: string_A = handles.hsl_current_string{1}(hsl_current_value{1}, :) string_B = ' ' z1_value, ' ' z2_value, ' ' z_value I am dealing with GUI, string_A is the value of the listbox, and string_B is the value I would like to add to the string_B and rep...

Strings, Strings and Damned Strings
I have an int variable (always <100) that I want to convert to a two character string, e.g. if myint = 1, mystr = "01" if myint = 81, mystr = "81" At the moment I can't figure out how to do this cleanly. Then I wish to push a bunch of these strings into an array, for example: typedef char LABEL[3]; LABEL mystrArray[100]; But having read a couple of tutorials I am still no clearer on the best way to do an "array of strings" in this situation, nor how to do it. Any help much appreciated! cheers, Ben Ben wrote: > I have an int variable (always &...

Strings, STRINGS, and crazy strings!
Oh my head... Someone, please bail this choking programmer out of a fix. Here's what I got. 1. A multi-line Textbox control. 2. Enter 3 lines of text (each line separated by hitting the Enter key). 3. In my routine, I transfer the Textbox.text into a string variable, say sString. 4. Then I parse this string with my Parsestring routine that places each individual string into an array called sWords() and the string count into lCount. 5. Next is a For/Next loop to print each string found in sWords() at the same starting point on my Picturebox control (the textbox is in this conta...

string.fine(string+string...
Hi after reading the docs, I was hoping this would work, but I can't find out why. string a = "I "; string b = "am"; int ego; if(sentence.find((a+b).c_str(),0)!= string::npos) ego++; from the docs **************** size_type find( const string& str, size_type index ); size_type find( const char* str, size_type index ); size_type find( const char* str, size_type index, size_type length ); size_type find( char ch, size_type index ); thanks Gary Wessle <phddas@yahoo.com> writes: > Hi > > after reading the docs, I was hoping this would work, ...

How to evaluate this string?
Hi all, I have a string like $string='My marks are ( (10+20)*2) ' i should be able to convert this string to $string='My marks are 60 ' the arithemaic expression may vary to any complexity. it may have logical expressions like '&&' or '||' etc. Can anyone help me out? Thank you Kaushik kaushik wrote: > Hi all, > I have a string like > $string='My marks are ( (10+20)*2) ' > i should be able to convert this string to > $string='My marks are 60 ' > > the arithemaic expression may vary to any complexity. it may ha...

String[] to String
/* I am writing this class to see the output of:args.toString();I want to see if the toString() method on the String[] will convertthe array contents into one string or it will write out it's typename,i.e. the <code>Class</code> class' name.As observed, the output is[java.lang.String@1693e2;which looks like the array's underlying type's name and the startingmemory address.*/public class Ats /*implying Array To String */{ public static void main(String[] args) { if ( args.length == 0 ) System.out.println("Usage: ats arg1 [arg2 [arg3...]]"); else Syste...

when string is not a string
Curious javascript sample. Consider the following code: var s = "asd" var f = function() { return typeof(this) } An expression typeof(s) returns true (as it is expected), but f.call(s) returns false! To make matters worse consider the following snippet: var s = "asd" var f = function() { return this instanceof String } An expression f.call(s) returns true, but (s instanceof String) returns false! The question is why call transforms this to an object? Is it made for unification, e.g. to make this iterable using 'for (var i in this)' loop?...

String or string
I am doing something where I do=20 If "force" || "spells" Puts "blah" When I use it it gives a warning about comparing strings, what's happening a= nd how do I fix it? Scratch.mit.edu. Go there! -gbear605= It doesn't seem to mind if those are pre-assigned ... ruby-1.9.2-p0 > if "force" || "spells" ruby-1.9.2-p0 ?> puts "blah" ruby-1.9.2-p0 ?> end (irb):3: warning: string literal in condition (irb):3: warning: string literal in condition blah => nil ruby-1.9.2-p0 > f = "forc...

string evaluation
Assume I have following arrays with sizes var1, var2, var3 ........ = 300 X 1 I wanted to copy a portion of these variables into another variables say for i = 10 : 20 strcat('var',num2str(i)) = strcat('var',num2str(i-9))(10:200); end What I actually wanted to do is var10 = var1(10:200); var11 = var2(10:200); ........ Is there a better way to do this in a loop, I could assign the variables individually but wanted to do in a loop if the variables are increasing. Thanks Did you create all of these variables in the first place? If so, that was you...

string of strings...
I got an array of id's : ids = [22443, 22468, 22371, 22218, 22472, 22377, 22245] I would like to get a string of strings (to be used in SQL WHERE..IN clause " '22443' , ' 22468' , ' 22371' , ' 22218' , '22472' , '22377' , '22245' " If a use ids.join(','), I get "22443,22468,22371,22218,22472,22377,22245" which is obviously not useful for SQL.... is there any shorcuts or should I concatenate each element ? thanks joss On 12/19/06, Josselin <josselin@wanadoo.fr> wrote: > I got an array...

string + string
Hi any idea why I am getting something like main.cpp:177: error: invalid operands of types ‘const char [11]’ and ‘const char [8]’ to binary ‘operator+’ when trying to compile something like int main(int argc, char* argv[]) { string a = ".........." + "......."; cout << a << endl; } how can I solve this, I have few lines and use + to concatenate them together. thanks Gary Wessle wrote: > Hi > > any idea why I am getting something like > > > main.cpp:177: error: invalid operands of types 'const char [11]' and 'const ch...

Evaluating Strings...
In php, I have an array called "q". The elements are: $q[0] = 2 $q[1] = 4 $q[2] = 5 $q[3] = 3 I'd like to be able to loop through this array via a While loop, and echo the contents of these array elements back to the screen. When I try something like: for($i = 0; $i < 4; $i++) { echo $q[i]; echo eval("$q[i]"); echo eval("\$q[" . i . "]"); } I get the "String" instead of the "Contents". For example, the output is $q[0] instead of 2, $q[1] instead of 4, etc. How can I fix this? Thanks. number1.email@gmail.com ...

a String which evaluates to itself.
Can you imagine any String that satisfies the following formula? aString = (Compiler evaluate: aString) It means aString evaluates to itself. '0'? No. It evaluates to an Integer. ''? No. It evaluates to nil. ''''''(2 letter string)? No. It evaluates to an empty String, outmost quotes are eliminated. Here is my example code. It produces a String exactly equal to its code text when evaluated. ================ cut here ================ | stringBank stringBankStream quoteChar quoteSubstitute stringDelimiter preQuoteString quotedStri...

Re-evaluating a string?
I'm writing a program to send data over the serial port. I'm using pyserial, and I'm on WindowsXP. When I use literals I can get the data accross how I want it for example: 1 2 3 4 5 6 serialport.write('!SC'+'\x01'+'\x05'+'\xFA'+'\x00'+'\r') 1=Get devices attention 2=Select channel on device 3=Rate for movement 4=Low byte of 16 bits 5=High bytes of 16 bits 6=Carriage return signaling command is over This command works as desired. Sends the first 3 ASCII characters, then some numbers in hex ...

evaluating a object string
var x = eval("{ 'flag' : 1 }"); alert(x); alert(x.flag); why doesn't the above work? On Mar 6, 12:17=A0pm, jman wrote: > =A0 =A0 =A0 =A0 =A0 =A0 var x =3D eval("{ 'flag' : 1 }"); > =A0 =A0 =A0 =A0 =A0 =A0 alert(x); > =A0 =A0 =A0 =A0 =A0 =A0 alert(x.flag); > > why doesn't the above work? Because the - eval - method treats its string input as a javascript program and a javascript program commencing with an opening brace is a program that starts with a block statement. That makes the content of the block statement a sy...

Evaluate string in Lisp
Hello, is it possible to evaluate a string in LISP? For example, there is a string "(pprint \"Hello World\")". Is it possible to evaluate this string? Regards Michael Michael H�nisch <Michael.Hoenisch@ascad.de> writes: > is it possible to evaluate a string in LISP? > > For example, there is a string "(pprint \"Hello World\")". Is it > possible to evaluate this string? > Combine eval with read-from-string -- Howard Ding <hading@hading.dnsalias.com> On Wed, 15 Sep 2004 14:44:48 +0200, Michael H�nisch <Michael.Hoeni...

String Evaluation #2
I need to evaluate a string expression which is made of some regular matlab functions and some created functions that don't take any arguments. For example: String = 'sin(plus( CreatedFunction1 , CreatedFunction2 ) )'; For sure I can get the job done by using the comand 'eval', but the thing is that it gets too slow (since I have thousands of strings to evaluate at a time). I also tried the function 'str2func' to generate a function handle to be evaluated by 'feval' but 'str2func' only seems to work with existing functions. The fastest way until ...

delaying string evaluation
Hi, I would like to partially expand a string and then further expand it later on when more information is available. I am currently using string interpolation with a reeval method suggested by Bill Kelly. class String def reeval(b = TOPLEVEL_BINDING) eval("<<END_REEVAL\n" + self + "\nEND_REEVAL\n", b).chomp! end end This lets me do stuff like this: expanded = "one" delayed = "two" s = "#{expanded} \#{delayed}" # => "one #{delayed}" s = s.reeval(binding) # => "one two" As a more...

evaluate string of variables
Hi I need to evaluate a string of vectors with for example str2num. so, what I have is a vector, x = [3 7 11 ]', and a string s1 = 'ones(size (x)) x x.^2 x.^3 x.^4 x.^5' , now I want to do the polynomial calculation in the string. str2num(s1) obviously doesnt work. I should also say that I am actually using comsol script, but it seems like str2num and eval is used the same way as in matlab. Thankful for any help. ...

numerical evaluation of a string
Hi, is there a way to evaluate in PHP a string like "2+3*5" ? I'm expecting 17 as a result. A way to achieve that would be to invoke the bc calculator but I was wondering if you can do such a thing directly in PHP? Cheers, Patrick ..oO(geantbrun) >is there a way to evaluate in PHP a string like "2+3*5" ? I'm >expecting 17 as a result. A way to achieve that would be to invoke the >bc calculator but I was wondering if you can do such a thing directly >in PHP? eval() Micha ...

Evaluating String Parameters
I am having trouble understanding how Parameters are evaluated (especially String Parameters). For many of my fixed point models, I use a Precision parameter to define the precision of an operation or port. Currently, Precision is specified as a String to support several different precision formats. In many cases, I specify the precision directly with a valid Precision string (for example "(1.8)"). In other cases, I would like to specify the precision with a parameter defined at a higher level in the hierarchy (i.e. as described in Section 2.5.1 Parameters in Hiera...

Evaluating string as var
Is there a way to do the following declare @var1 varchar select @var1 = "@var2 = 5" declare @var2 varchar select @var2 = 5 set rowcount 5 select * from the..table where @var1 so that rows are actually returned. In a nut shell we have a table that has parts of a where clause. vars are being passed in, and we want to append the selected clause to the statement. in the above example in ecmascript I could just do eval(@var1) in the select and wit would return rows...is there a sybase equivilent??? Do not write code like this. You are supposed to know what you a...