Dynamically calling variables (it's not what this sounds like!)
조회 수: 8 (최근 30일)
이전 댓글 표시
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
Mathieu NOE
2021년 11월 10일
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
채택된 답변
Dave B
2021년 11월 9일
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
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!