Reading column vectors from table with header text as variable name
7 次查看(过去 30 天)
显示 更早的评论
I have an excel file with first row as header name for the corresponding column, each column has 4999 entries and 85 different readings. I want to load all the column vectors as a seperate variable. The variable name should be same as the header name from the excel file.
T = readtable("sample_data.csv");
S = T.Properties.VariableNames;
for i = 1:length(S)
assignin("base", S{i}, T.(S{i}))
end
This is what I came up with, but someone suggested not to use assignin command. Can some one suggest better alternative to this, also I don't want to seperate the column vectors manually.
Thank you.
4 个评论
Stephen23
2025-7-2
编辑:Stephen23
2025-7-2
"I need to extract columns from the table and the extracted variable should have the same name as the header."
Your approach would most likely make processing your data harder. I strongly recommend that you provide us some context of what you are trying to achieve, and most likely we can show a much better way to design your data: one much better approach is to use the table which you already have.
"Thanks for helping."
回答(1 个)
Matt J
2025-6-29
编辑:Matt J
2025-6-29
You should never be letting code decide what to name variables. You should know the names. If you do, just use readvars,
If you have too many variables to write out manually, then it is not clear why you would want to split the table into separate variables in the first place.
4 个评论
Matt J
2025-7-2
编辑:Matt J
2025-7-2
I intend to name the variables same as the header name (i.e., sensor name).
Yes, I also understood your intent, but I still recommend against it. If the reason you are trying to avoid manually creating each variable is because there are too many of them, then you should abandon the idea. Use the T table variable to access the data. Packaging many variables together so that you don't have to manipulate them one by one is the whole point of a table.
S = table2struct( readtable("sample_data.csv") ,'ToScalar',true);
structvars(S)
This will not create the variables for you, but it will print the lines of code needed to do so, thereby sparing you manual work.
Siddharth Bhutiya
2025-7-8
+1 to what Matt and Stephen mentioned about not trying to dynamically name workspace variables. Its a slippery slope that would lead to inefficient/incorrect code. Lets say you are somehow able to create workspace variables with the desired names, now if you don't know the names beforehand how would you write any code that then uses those variables once you've created them?
As Matt mentioned the whole point of tables is package related data together, so why not directly use the table? Are you running into any problems when you try working directly with the table?
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!