0
$\begingroup$

I was wondering if there is a way of Mathematica to read a string or number and create variable with that name.

For instance imagine that I have a file with the word data1. I would want to create a variable called "data1".

On the other hand, imagine that I read a number from that file "N". And then I want to do a for cycle to create N variables called data%d where %d goes from 1 to N. Is there a way to do this in Mathematica?

Thank you!

EDIT:

So using the suggestion I was given in fact doing this piece of code works:

data1=ToExpression[data1]
data1 = 3
data1

It prints out 3.

However when I do:

Data = {{"Field1", "Field2", "Field3"}, {"LP", 30, 2}}
For[i = 1, i <= Length[Data[[1]]], i++, Data[[1]][[i]] = ToExpression[Data[[1]][[i]]]];
For[i = 1, i <= Length[Data[[1]]], i++, Data[[1]][[i]] = Data[[2]][[i]]];
Field1

Field1 prints out Filed1 instead of printing out LP. Any guess of what I am doing wrong? I want to be able to manipulate variable Field1 with value LP. Thank you.

$\endgroup$
6
  • $\begingroup$ I would want to create a variable you mean you want to convert string to a Symbol of that name? Then use ToExpression["data1"] And for the rest you can do Table[ToExpression["data" <> ToString[n]], {n, 1, 10}] !Mathematica graphics I think your question has been asked before but hard to find now. $\endgroup$
    – Nasser
    Commented Jan 2, 2023 at 8:31
  • $\begingroup$ Yes that was what I've meant, thank you! $\endgroup$ Commented Jan 2, 2023 at 8:50
  • $\begingroup$ There is also the function "Symbol" $\endgroup$ Commented Jan 2, 2023 at 8:51
  • $\begingroup$ Also have a look at Unique. $\endgroup$
    – user21
    Commented Jan 2, 2023 at 9:15
  • 2
    $\begingroup$ Please consider using Association, it is rarely justified to create symbols on a fly. It is costly and cumbersome. $\endgroup$
    – Kuba
    Commented Jan 2, 2023 at 10:47

0