A for loop extracting every new variable into column vectors?
1 view (last 30 days)
Show older comments
Hi! I have the following stacked table, and I need to be able to extract/refer to every new element that appears at ChElem_Indicator (column 8) with the correspondent value that appears at ChElem (column 9). The ChElem_Indicator contains repeated data, with the elements (for example "Si") appearing hundreds of times.
Every time a new ChElem_Indicator variable appears, I'd like to create a column vector (with the name of that variable) that extracts the corresponding value from ChElem column. Scanning the entire table, my goal is to end up with, for example, a column vector "Si" with all values which are related to "Si", and to have this for all the different variables that appear in ChElem_Indicator column (not only "Si"). I think a for loop is what I need, but I don't know how to incorporate the part "for every new variable".
Any ideas/suggestions? Thanks in advance!
2 Comments
Stephen23
on 6 Feb 2018
Edited: Stephen23
on 6 Feb 2018
'I think a for loop is what I need, but I don't know how to incorporate the part "for every new variable".'
Do NOT do this! Magically accessing variable names in a loop is how beginners force themselves into writing slow, complex, buggy code:
'my goal is to end up with, for example, a column vector "Si" with all values which are related to "Si", and to have this for all the different variables that appear in ChElem_Indicator column (not only "Si").'
'Any ideas/suggestions?'
Use one of the table class methods to group the rows based on that column, such as
or
Answers (1)
Guillaume
on 6 Feb 2018
[groupid, groupname] = findgroups(ClustSEMdata.ChElem_Indicator);
elements = splitapply(@(v) {v}, ClustSEMdata.ChElem, groupid);
result = cell2table(elements.', 'VariableNames', groupname)
It sounds like you want to create individual variables for each element, which would be a very bad idea. Putting them in a table as above, a cell array, a map, or a structure would be a lot better.
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!