Dynamically calling variables (it's not what this sounds like!)
7 views (last 30 days)
Show older comments
Hi everyone,
I have five files that have almost the same name except for one term that is added in the end, like "filename_A", "filename_B" etc., and the columns in these files are almost the same up to that last term as well, e.g.
filename_A: column1_A column2_A column3_A ...
filename_B: column1_B column2_B column3_B ...
I would like to loop through the different files and the different columns, but I cannot figure out how to dynamically bring up the names in the loop with sprintf or similar functions. I know people strongly advise against dynamically creating variables. But is that also the case for calling them?
I suppose an alternative would be to have created my files/named the columns in a better way, but I don't know how. Any help is greatly appreciated because I run into this problem all the time with the way my data is structured!
5 Comments
Mathieu NOE
on 10 Nov 2021
yes sure - there are many ways to tackle each specific problem and it's completely normal that you chose the one that matches best your application
... myself I learn a lot from other's answers and that's the positive aspect of this forum. There's always something new to (re) discover and I do also keep interesting answers in my PC for future use
all the best
Accepted Answer
Dave B
on 9 Nov 2021
I think, if I read your question correctly, you're saying:
- You have files with a suffix
- The suffix determines the names of variables in a table?
- You want to do something where you can use the filename's suffix to refer to the table variable names
If that's the case, I suspect the tricky bit is the syntax for referring to a table variable using a name. (Note the parantheses below, the general syntax is table.(dynamicname), which also works for stucts)
t = table(zeros(5,1),ones(5,1),'VariableNames',["Var_A" "Var_B"]);
suffixes=["_A" "_B"];
for i = 1:numel(suffixes)
disp(t.("Var" + suffixes(i)))
end
But if I missed something, it would certainly be helpful if you included some example data files or a reduced example to show what you're trying to accomplish.
(And yes I think most folks would agree it's be better to not create the files this way, but it's hard to say how you should change that code because you didn't give much info, maybe that's a separate question?)
5 Comments
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!