How to call/create column variables from changeable table?
1 view (last 30 days)
Show older comments
Ana Castanheiro
on 29 Jan 2018
Commented: Peter Perkins
on 15 Apr 2020
Hi! I have this table (see image) from which I need to call all individual columns using their column names. For example, for using a variable called Fe to retrieve the Fe column, and so on for all columns. I know I can do this by using tablename.Fe, but I'm looking for a more efficient and automatic way, because:
- there are dozens of columns to be retrieved
- the order/size of the initial data table differs from sample to sample (especially because of this!)
In the end, I want to be able to use these variables for further operations, for example to do cluster analysis by focusing on specific elements only (e.g. data1 = [S Al Si Ca Fe];).
Any help is really appreciated!
0 Comments
Accepted Answer
Peter Perkins
on 30 Jan 2018
Edited: Peter Perkins
on 31 Jan 2018
I think what you are looking for is either
data1 = data(:,{'S' 'Al' 'Si' 'Ca' 'Fe'})
or
data1 = data{:,{'S' 'Al' 'Si' 'Ca' 'Fe'}}
depending on whether you want a subtable or a numeric matrix. And of course you could substitute [10 7 8 13 17] for those names in either case. There's a whole section in the doc about table subscripting.
2 Comments
Jörg Ho
on 31 Mar 2020
Hi,
I have a similar problem, but the solution won't fit. 'data1' is a table as well as 'data'. What I want is to create a number of arrays (in this example would it be for the names of the arrays: data.Properties.VariableNames) with its data from the table.
I thought of a loop over the names like:
for item=data.Properties.VariableNames
? = table2array(data(:,item))
end
But, how do I get the value of 'item' in place of the '?'?
Thanks a lot,
Jörg Ho
Peter Perkins
on 15 Apr 2020
Very likely you do not want to do that. Unless you have a very small number of variables in your table, you will end up with many things in your workspace, and no good way to address them. If you do have only a very small number of variables in the table, do it by hand.
You have those data in a table. You can refer to them by name using dot subscripting, for example
data.ItemName
and you can easily loop over them, referring to each one as
data.(data.Properties.VariableNames{i})
or even
data.(i)
" 'data1' is a table as well as 'data'."
No, it isn't if you use braces, not parentheses. More information in the doc section I referred to.
More Answers (0)
See Also
Categories
Find more on Logical 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!