renaming a variable, or creating a dynamic variable name
古いコメントを表示
Hi folks,
I read on here that creating dynamic variable names is bad programming practice, so was hoping to get some help with a problem I'm facing.
I have a cell array containing 54 tables. Each table has a unique name associated with it which is not present in the cell array or data table. It is recorded in a string cell called "sampleNames".
I need to split each table in the cell array into its own table, with each table having the name of the sample it is related to. For example:
sampleAAA = data{1, 1};
...
...
...
sampleZZZ = data{1, n};
where "data{}" is the cell array containing all my tables, and "sampleAAA" would be sampleNames(1).
Is there a way to do this?
Thanks in advance!
3 件のコメント
Walter Roberson
2021 年 11 月 3 日
Yes, there is a way to do it, but why do you want to do that? Why not store the tables in a cell array, or at most as fields in a struct? Why do you need individual variables for every column of the every table ?
Teshan Rezel
2021 年 11 月 3 日
"I need to split them because I need to analyse each table individually"
I doubt that you need to split your data into separate variables just to analyse them.
"...doing so in the current state of the data would be incredibly messy and convoluted, leading to errors."
Really, why?
You can trivially access the names and the data using the same indices, I don't see any reason why that would have to be "messy and convoluted". In contrast, the approach you are attempting is more complex and much less efficient than indexing.
Your mistake is mixing meta-data with code: best avoided if you want to write simple, robust, efficient code.
採用された回答
その他の回答 (1 件)
If the elements of sampleNames are valid MATLAB identifiers I think Walter Roberson's suggestion to store each table in a field of a struct array seems reasonable. Each element in sampleNames would give the name for the field containing the corresponding table array.
Another possibility is to concatenate the table arrays together after adding one variable to each array, call it sampleName. Each row of this new variable would contain the name from sampleName of the table that contributed the row to the larger table.
load patients
VN = {'Name', 'Height', 'Weight'};
T1 = table(LastName(1:5), Height(1:5), Weight(1:5), 'VariableNames', VN);
T2 = table(LastName(6:10), Height(6:10), Weight(6:10), 'VariableNames', VN);
T1.sampleName = repmat("Table 1", height(T1), 1)
T2.sampleName = repmat("Table 2", height(T1), 1)
T = [T1; T2]
If then you needed to process each table's data separately you could use groupsummary or grouptransform with sampleName as the grouping variable. Or you could select rows using that variable:
T3 = T(T.sampleName == "Table 1", :)
T4 = T(matches(T.sampleName, 'Table 2'), :)
カテゴリ
ヘルプ センター および File Exchange で Tables についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!