필터 지우기
필터 지우기

Concatenate dynamical variables [A1;A2;A3.A4;AN) in one script line

조회 수: 6 (최근 30일)
Leandro B. Castellanos
Leandro B. Castellanos 2018년 8월 13일
댓글: Leandro B. Castellanos 2018년 8월 16일
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
Stephen23
Stephen23 2018년 8월 14일
편집: Stephen23 2018년 8월 14일
"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.
Leandro B. Castellanos
Leandro B. Castellanos 2018년 8월 16일
Wonderfull answer, thanks Mr. Stephen Cobeldick

댓글을 달려면 로그인하십시오.

답변 (1개)

James Tursa
James Tursa 2018년 8월 13일
편집: James Tursa 2018년 8월 13일
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:

카테고리

Help CenterFile Exchange에서 Workspace Variables and MAT-Files에 대해 자세히 알아보기

제품


릴리스

R2018a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by