Put variable names into a cell array or string array
9 次查看(过去 30 天)
显示 更早的评论
I have a number of similarly named variables in my script, eg
VarableAB
VarableDEF
VarableGHIJK
:
VarableZ
How can I get all these variable names into a cell array or a string array that I can loop round to do the same thing to each variable?
7 个评论
Stephen23
2024-10-10
移动:Rik
2024-10-12
"I am not a programmer, just a scientist who tries to use MATLAB to analyse data."
Me too! That is, if mathematics counts as a type of science :)
"Maybe I did paint myself into a corner with this problem, but I didn't know any better."
We all start new topics knowing nothing about them.
"I struggle with many concepts in MATLAB and other programming languages and don't feel that I have the time to learn them properly."
Using vectors, matrices, arrays and indexing are not esoteric things that only programmers understand, they are really very fundamental to using MATLAB:
采纳的回答
dormant
2024-10-10
1 个评论
Stephen23
2024-10-10
编辑:Stephen23
2024-10-10
"Is this so bad?"
From the MATLAB documentation: "A frequent use of the eval function is to create sets of variables such as A1, A2, ..., An, but this approach does not use the array processing power of MATLAB and is not recommended. The preferred method is to store related data in a single array. If the data sets are of different types or sizes, use a structure or cell array."
更多回答(1 个)
Rik
2024-10-10
Adding to the comments: you are putting data (a description and therefore a property) in the variable name. That is where your design is going wrong.
What you should probably have done is to write each of them to a separate mat file, or make them all fields of a struct.
When you have a bunch of mat files you can use dir to generate the array to loop over. If you choose to make it a struct array you can use fieldnames like this:
Varable.AB=1;
Varable.DEF=2;
Varable.GHIJK=3;
for fn=fieldnames(Varable).'
current = Varable.(fn{1});
fprintf('value of field %s is %d\n',fn{1},current)
end
1 个评论
Stephen23
2024-10-10
编辑:Stephen23
2024-10-10
Supplementing this answer: using a structure array and storing that meta-data in its own field also allows the use of meta-data which are not valid fieldnames:
S(1).data = 11;
S(1).meta = 'AB';
S(2).data = 23;
S(2).meta = 'CDE';
S(3).data = 99;
S(3).meta = 'This is not a valid fieldname';
for k = 1:numel(S)
fprintf('The value of element %d is %d and has text "%s"\n',k,S(k).data,S(k).meta);
end
and makes it easy to obtain data based on substrings on the meta-data:
iwant = 'valid'; % some substring
idx = contains({S.meta},iwant);
S(idx).data
Although rather than matching substrings you might as well store each meta-data value in its own field:
In short: better data design make your code more robust (as well as neater, more efficient, etc.).
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Structures 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!