0

If for instance I have a variable xa=2, and then I construct a string by joining 'x' and 'a', how can I make this new string have the value 2?

xa=2;
var=strcat('x','a');

The result of this is var=xa, but what I want is var=2.

Thank you

8
  • Use eval() : mathworks.com/help/matlab/ref/eval.html EDIT: Code tested, posted an answer. Commented Feb 11, 2015 at 13:52
  • 4
    You can do this, but you shouldn't do it... A map/dictionary would be a better approach, even though also not very idiomatic in MATLAB. Commented Feb 11, 2015 at 14:02
  • Why would you want to do such an awful thing? Commented Feb 11, 2015 at 17:27
  • 1
    There are at least 5 different reasons why eval should not be used. Commented Feb 11, 2015 at 22:54
  • The reason why I wanted to do it is because the script prompts the user for a project folder, which can be for instance 'C1'. After that the script will go into that folder and load 'positiveInstancesC1.mat', and the variable 'positiveInstancesC1' will be used several times afterwards. So concatenating strings was what I could think about to be able to make the script work only with the input of the folder name, and not changing the variable in the script. But probably there is a better way to do it I am unaware about. Commented Feb 12, 2015 at 9:14

1 Answer 1

4

Use eval():

var = eval(strcat('x','a'));

It will "evaluate" the string 'xa' and translate it to the value of the variable xa.

Source : MATLAB documentation

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.