Reputation: 13
I am attempting to write a script to import a large .txt file containing multiple columns of data into seperate variables within Matlab.
I have reached a stage where I have my 7 datasets:
Var1= 3230 x 1 double
Var2= 3230 x 1 double
Var3= 3230 x 1 double
Var4= 3230 x 1 double
Var5= 3230 x 1 double
Var6= 3230 x 1 double
Var7= 3230 x 1 double
and an array containing all of the variable names in different cells:
nameArray= 1 x 7 cell
My question is: how do I create variables with the same names as those within nameArray and subsequently populate them with data from my datasets?
Upvotes: 1
Views: 482
Reputation: 12701
You have three options:
Use assignin
:
assignin('caller', nameArray{1}, Var1)
assignin('caller', nameArray{2}, Var2)
...
This will create a variable with name nameArray{1}
and value Var1
in the namespace of the caller.
Build a struct:
x = struct()
x.(nameArray{1}) = Var1
...
This builds a struct with dynamically assigned fields.
As @Scott suggests in his answer: Use readtable
:
T = readTable('mydatafile.txt')
This yields a similar result as option 2. But T
is of type table
and not struct
. Tables are availble in Matlab versions R2013b and newer.
And of course you should use a loop
Upvotes: 2