Concatenate dynamical variables [A1;A2;A3.A4;AN) in one script line
3 views (last 30 days)
Show older comments
To continue with the development of a program, I would need to know how to make a concatenation of dynamic variables A1, A2, A3, AN, I know the common procedure cat [1, A1, A2, A3], how several dynamic AN variables will be generated, I would like to know how I can do a scrip concatenated AN's dynamics variables.
2 Comments
Stephen23
on 14 Aug 2018
Edited: Stephen23
on 14 Aug 2018
"To continue with the development of a program..."
you should fix the part of your code that created lots of variables like that, so that they are all conveniently in one cell array C. Then your task is trivially easy:
cat(1,C{:})
By designing your data better, you can make your code much simpler, more efficient, and less buggy!
When beginners write code that requires accessing variable names dynamically, they force themselves into writing slow, complex, buggy code that is hard to debug. Which is why the MATLAB documentation specifically recommends avoiding doing this: "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."
So the best solution is fix the code where those variables are created. I doubt that you sat and wrote them all out by hand, so probably they were created by importing some data from some files, in which case it is trivial to fix using a cell array and indexing. Another tip is to always load data into a variable:
S = load(...)
because this makes processing the data much simpler and reduced the risk of bugs.
In any case, it is much better fix the variables where you create/load them so that they are stored in a simple cell array, rather than trying to write slow hack code later.
Answers (1)
James Tursa
on 13 Aug 2018
Edited: James Tursa
on 13 Aug 2018
Best advice is to back up and rewrite the code that is creating these A1, A2, etc variables in the first place. Instead, use something like cell arrays so you would have A{1}, A{2}, etc instead. Then the answer is simple:
result = [A{:}];
See this link:
0 Comments
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!