MATLAB: Convert String to Expression for IF Statement

logicstring

Issue: conditional expression for IF-statement is dynamic
if cond
a = 1;
else
a = 2;
end
"cond" will change according to input strings/values at each run. It can have any logic combination (<, >, =, &&, ||) and any length. Some examples:
  • "data1 > 10"
  • "data1 > 10 && data1 < 1000"
  • "data1 > 215 || data1 < -10"
  • "data1 > 35 && data2 = 2 && data 3 < 1000”
Conditions expressions will be read in as strings. Is there a way to convert the string to an executable expression?
Example: Running an equivalent version of the code
data = 10;
cond = 'data > 30';
if cond
a = 1;
else
a = 2;
end
returns a = 2.

Best Answer

data<1000
That will return a logical (true or false value).
parseCond=@(data) data<1000;
That will create an anonymous function that returns a logical. You can expand it easily like this:
parseCond=@(data) false;
parseCond=@(data) parseCond(data) || data<1000;
val=800;
parseCond=@(data) parseCond(data) && data>val;