Is it possible to identify variables in the workspace that contain a string and save the identified variable with another name?
조회 수: 29 (최근 30일)
이전 댓글 표시
Is it possible to identify variables in the MATLAB workspace that contain a certain string and save that variable with a new name?
For example, search for variables containing "Position" then save the found variable with a new name? I'm working with data that is imported into the workspace where the exact variable name often changes but always contains a common string.
댓글 수: 1
Stephen23
2024년 1월 29일
편집: Stephen23
2024년 1월 29일
"Is it possible to identify variables in the MATLAB workspace that contain a certain string and save that variable with a new name?"
It is possible, if you really want to force yourself into writing slow, complex, inefficient, insecure, buggy code that is hard to debug:
"I'm working with data that is imported into the workspace where the exact variable name often changes but always contains a common string."
So far you have not told us the most important information: how are you importing that data into the workspace? The place where you import that data would be best place to fix this very badly designed data, not later once it is already in the workspace.
채택된 답변
Stephen23
2024년 1월 29일
Assuming that you are LOADing some MAT files, then the best approach is to avoid your situation entirely, for example by LOADing into an output variable:
S = load(...)
If each MAT file contains exactly one variable and you do not (easily) know its name, then you can do this:
C = struct2cell(load(..));
D = C{1};
Because you did not give any concrete information this is general advice. If you actually showed us the code you use to import into the workspace (and even better uploaded some sample data files) then we could actually write some working code very quickly.
댓글 수: 3
Stephen23
2024년 1월 30일
편집: Stephen23
2024년 1월 30일
"where "variableName" is the variable that can change name between data files."
As far as I can tell from a brief reading of TDMS Reader documentation, the function TDMS_GETSTRUCT actually returns a structure. So what you have are actually called fields (they are not called variables):
You can easily access the fields of a structure dynamically using e.g. FIELDNAMES() to get their names and then use dynamic field names to access their content:
Field names are just text, so of course you can use any text tools to match/identify the particular fields that you want (e.g. using STARTSWITH, CONTAINS, etc).
So in the end, you might have something like this (untested of course):
F = fieldnames(Struct1.A);
X = <some logic to identify one field name in F>
D = Struct1.A.(F{X})
It also depends on the sizes of those structures, how many fields you need to access, etc.
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Whos에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!