manipulating through sequential variables using for loop
5 views (last 30 days)
Show older comments
Hi,
(I tried to search on the forum and found many similar questions and answers, but none seems to be exactly the same as my question, so here we go...)
I have successfully loaded 32 sequential variables from a MAT file.
A_001, A_002, ..., A_032
Each variable is an array of different length (1 x N). I want to manipulate these variables (e.g. plot all 32 of them), and I want to use a for loop to do this. How can I do this? I imagine things will be a lot easier to handle once I create a structure containing all of these variables, but I have no idea how to do that.
It looks like eval can help me do that, but many suggest not to use eval.
Many thanks in advance!
Hemmings
1 Comment
Stephen23
on 7 Oct 2015
Edited: Stephen23
on 7 Oct 2015
Both creating and accessing of dynamically named variables (such as sequentially numbered ones) is a really bad idea, leading to slow buggy code. Avoid creating numbered variables, and use simple numeric arrays, cell arrays or non-scalar structures instead:
Here is a discussion of why it is a bad idea to include meta-data (such as an index) in a variable name:
Accepted Answer
Walter Roberson
on 6 Oct 2015
3 Comments
Walter Roberson
on 7 Oct 2015
If you need to access by index a lot, struct2cell and index the cell.
If the struct does not have its fields in the order you want to index, you can create a index vector:
fn = fieldnames(S);
fnidx = str2double( regexprep(fn, '^A','') );
[~, indexvec] = sort(fnidx);
Sc = struct2cell(S);
Sc{indexvec(k))
Stephen23
on 7 Oct 2015
Edited: Stephen23
on 7 Oct 2015
This whole situation could have been avoided by planning the data better: use of a multidimensional numeric array, a cell array or a non-scalar structure would avoid the need to create dynamic fieldnames and allow the data to be accessed simply using indeices. For example if the matrices were in a cell array named data:
S = load(filename);
X = S.data;
X{1} % first matrix
X{2} % second matrix
... etc
S = load(filename);
X = S.data;
X(1).fieldname % first matrix
X(2).fieldname % second matrix
Y = [X.fieldname] % concatenate into one numeric array
Z = {X.fieldname} % convert into cell array of numeric arrays
More Answers (0)
See Also
Categories
Find more on Structures 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!