0
votes

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

1
Use eval() : mathworks.com/help/matlab/ref/eval.html EDIT: Code tested, posted an answer. - Yellows
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. - knedlsepp
Why would you want to do such an awful thing? - beaker
There are at least 5 different reasons why eval should not be used. - rayryeng
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. - Zynk

1 Answers

4
votes

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