0

This might be a very bizarre question (and probably I might be advised against doing such a weird thing) but if I have a string as in v_str ='var_name' and I want to transform the contents of that code into the actual code, is that possible in MATLAB? As in:

v_str = 'var_name'
x = make_string_to_code(v_str)

translates to the functioning code:

x = var_name

which simply transforms the string to actual code.

The only way I thought of doing this is by writing a file with that code and then on the next line executing that fine, but I wanted to avoid writing files every time that I want to do this.

Also, why is this so not recommended? Why is it so bad?

2
  • 2
    Yes, but you don't want to. Commented Mar 21, 2016 at 17:13
  • @excaza thank you. :D somehow I missed it. Commented Mar 21, 2016 at 17:18

1 Answer 1

1

You can use eval, but that doesn't mean you should, as others mentioned.

v_str = '2 + 2'
eval(['x = ' v_str]) % x = 4;
x = eval(v_str); % x = 4;

The documentation of eval can be found here: eval

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

3 Comments

so making variables out of strings is NOT recommended? Why so? (sorry if this is an obvious question)
@CharlieParker because it's bad programming practice in general to have no idea where your variables are coming from; it makes it very difficult to debug. You're also blindly executing any string, which is not at all secure. It's also highly inefficient, MATLAB's JIT compiler cannot optimize eval statements.
@CharlieParker See excaza's first comment on your original post.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.