0
$\begingroup$

I am trying to generate different variables in function of a loop index. In example: generating a list with var1 = 1, var2 = 2, ...

For[i=0,i<5,i++, ToExpression[ "var"<>ToString[i] <> " = " <> ToString[i]] ]

I learnd how to use the 'ToExpression' function and it worked for the example avobe. But when I want to, for example import data, I have to add double quotes "" inside the ToExpression function, then I get wrong results, for example.

For importing files in different variables:

For[i = 0, i < 8, i++,
    ToExpression[ 
  "band0" <> ToString[i] <> 
    " = Import["/home/data/band0 "<> ToString[i] <>".txt "]" ]
         ]

It looks like confuses Mathematica because each block around quotes is considered by separate.

Then, what could I do?

$\endgroup$
  • $\begingroup$ Did you try escaping the quotes inside the string? \"/home/data/band0 \" rather than "/home/data/band0 ". $\endgroup$ – jjc385 Apr 27 '18 at 22:09
  • 2
    $\begingroup$ what is it exactly you are trying to do with this code? why are you appending "band0" to the data imported? what you are doing do not make much sense and I would suggest to avoid such hacks using ToExpression. Unless it is necessary. $\endgroup$ – Nasser Apr 27 '18 at 22:12
  • 3
    $\begingroup$ Echoing Nasser comment, don't use hacks. The correct thing to do is, for example, Table[var[i] = i, {i, 0, 4}] instead of your ToExpression trick. $\endgroup$ – AccidentalFourierTransform Apr 27 '18 at 23:35
  • 2
    $\begingroup$ Agree with the above posters. In general, one should avoid the use of ToExpression as it can be unsafe. You can escape quotes within your string using \" when a quote appears within a string, but again, this is not a good practice. You are trying to create a bunch of variables for different variables, correct? Why not do something like data = Import /@ listOfFiles and then you can access the data via something like data[[i]] instead? $\endgroup$ – enano9314 Apr 28 '18 at 1:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.