samstevens92
samstevens92

Reputation: 13

Creating variable names using cells from an array in Matlab

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

Answers (2)

hitzg
hitzg

Reputation: 12701

You have three options:

  1. 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.

  2. Build a struct:

    x = struct()
    x.(nameArray{1}) = Var1
    ...
    

    This builds a struct with dynamically assigned fields.

  3. 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

Scott
Scott

Reputation: 99

You might want to consider using T = readTable('mydatafile.txt'). This allows you to load a file with seperate columns and access those colums using their column name, for example like this: T.MyFirstColumn. See the manual on readtable for some examples.

Upvotes: 2

Related Questions