4
cond = 'a==1';
a=1;
if (cond)
b=0;
end

Hi! Is there a way to do the thing I wrote above? In a text variable I need to write a condition (even a complex one, using && and || too) and then in the IF statement I simply insert the variable. I tried this example but sadly it didn't work. Can you solve it?

Edit: more information to you!
I am backtesting different trading strategies for a project.
Inside the general M-file, I make use of a function for each strategy I need to tests. Each strategy gets in input data about the current situation and then the function evaluates the behavior of the trading strategy according to the data (and also according to margin requirements and other stuff independent from strategy). The only thing that is different in each function, is the entry or exit rule. Each strategy has for sure entry and exit condition (for instance, "open a long position when ... and ..." or "close a short position when ... or ...").
In the main M-file I am using a cycle to simulate the time passing by, but I want to implement a further external cycle which represents the number of the strategy tested. Furthermore, up to now each condition in IF-statements is written by hand and I would like to obtain a unique function (no more 1 for each strategy as now) that according to the cycle index of the strategy, would pass the entry and exit conditions taken from a matrix of strings.

I hope it could be possible to do that.

4
  • 2
    I think you mean cond = 'a==1', 'a=1' is not a condition it's an assignment. Commented May 15, 2015 at 8:41
  • 2
    Yep, you want a==1 to start, then I guess you will need to use if eval(cond). Commented May 15, 2015 at 8:41
  • As mentioned in the answer - this is not a good idea!! If you end up in a situation where you think you need to use evil eval they you probably need to rethink your problem.... Commented May 15, 2015 at 9:07
  • There are some legitimate uses of eval (although not many). This isn't one of them (without having more background on the question). Commented May 15, 2015 at 11:08

1 Answer 1

7

I think this is what you want:

cond = 'a==1';
a=1;
if eval(cond)
  b=0;
end

However, eval is evil. Try not to use it if possible: http://blogs.mathworks.com/loren/2005/12/28/evading-eval/

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.