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

Zynk
  • 95
  • 1
  • 10
  • Use `eval()` : http://www.mathworks.com/help/matlab/ref/eval.html EDIT: Code tested, posted an answer. – Yellows Feb 11 '15 at 13:52
  • 4
    You *can* do this, but you *shouldn't* do it... A [map/dictionary](http://stackoverflow.com/questions/9850007/how-to-use-hash-tables-dictionaries-in-matlab) would be a better approach, even though also not very idiomatic in MATLAB. – knedlsepp Feb 11 '15 at 14:02
  • Why would you want to do such an awful thing? – beaker Feb 11 '15 at 17:27
  • 1
    There are at least 5 different reasons why `eval` should not be used. – rayryeng Feb 11 '15 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. – Zynk Feb 12 '15 at 09:14
  • @Zynk Ordinarily, the values stored in the .mat files where you need to perform the same calculations on each value will all use a consistent variable name. Then as you load each one, the contents of that variable in your script changes and that's what you work on. – beaker Feb 13 '15 at 19:18
  • @beaker, I understand what you say but I don't know how to use that information in what I want to achieve – Zynk Feb 16 '15 at 12:11
  • @Zynk Without more information on what you want to achieve and some sample code, it's hard to get too specific. – beaker Feb 16 '15 at 18:32

1 Answers1

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

Yellows
  • 693
  • 4
  • 14