Look-up table row and assign values to individual variables
3 views (last 30 days)
Show older comments
Suppose I have a table with names listed in the first column. The remaining columns list parameters associated with the name (let's say: Age, Height, Weight).
I want to be able to specify a name from the first column and load variables with names specified by the remaining column headers and values given by the row corresponding to the name I've specified. For example:
rowName = 'John'
[vars] = load_table_variables(rowName,Table)
Which would result in variables called 'Age', 'Height', and 'Weight' that can be used directly later in the script.
1 Comment
Stephen23
on 14 Aug 2018
"Look-up table row and assign values to individual variables"
This is not recommended. Dynamically defining/accessing variable names is how beginners force themselves into writing slow, complex, buggy code. Read this to know more:
Clearly if you know the names of those variables then there is nothing stopping you from allocating the table columns to them:
X = T.X
Y = T.Y
... etc
but doing this "automatically" is not recommended.
"Which would result in variables called 'Age', 'Height', and 'Weight' that can be used directly later in the script."
Note that data already exists in the table, there is no point in duplicating it, when you can already trivially access it from the table.
Answers (3)
dpb
on 14 Aug 2018
You can create duplicate variables if wanted, but I'd suggest in the end it'll be better to use table addressing with the various functions for processing table data like varfun, rowfun, findgroups/splitapply.
To retrieve the numeric data from your hypothisized table you can write
john=T{'John',{'Age','Height','Weight'}};
if you use the name as the table rownames property.
If it's actually a column in the table, syntax is just slightly different; you have to do the lookup yourself...
john=T{contains(T.FirstName,'John'),{'Age','Height','Weight'}};
Each will return an array of however many records there are for John by 3 for the three variables (presumably double).
It's really not a good idea to "poof" variables into the workspace.
0 Comments
Jeff Miller
on 14 Aug 2018
Another option is to return a structure containing all the variables you want as its fields. For example,
rowName = 'John'
s = load_table_variables(rowName,Table)
would return s having the fields s.Age, s.Height, s.Weight, etc. Instead of loading completely separate variables, you are loading fields of a structure, but the fields can be used just like variables.
0 Comments
Peter Perkins
on 24 Aug 2018
If the names are unique, make them row names.
JohnsData = allData('John',{'Age', 'Height'})
or perhaps allData{'John',{'Age', 'Height'}} if all the values were numeric.
0 Comments
See Also
Categories
Find more on Tables in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!