A for loop extracting every new variable into column vectors?
1 次查看(过去 30 天)
显示 更早的评论
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 个评论
Stephen23
2018-2-6
编辑:Stephen23
2018-2-6
'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
回答(1 个)
Guillaume
2018-2-6
[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.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!