creating matrices in a loop
3 views (last 30 days)
Show older comments
I am trying to create matrices in a for loop as below: for a=1:5 u_a=[]; end; My intention is to get u_1,u_2,...,u-5. However, it is creating u_a for five times. Can anyone help in this regard. Thanks in advance!
1 Comment
Stephen23
on 20 Jul 2017
"Can anyone help in this regard"
Yes, use indexing. Indexing is much better.
Answers (1)
Stephen23
on 20 Jul 2017
Edited: Stephen23
on 20 Jul 2017
"My intention is to get u_1,u_2,...,u-5. ... Can anyone help in this regard"
Do not do this!
While it is possible to magically create variable like that, doing so will make your code slow, buggy, hard to read, hard to debug, inefficient, a security risk, etc,. Here is what the MATLAB documentation says about magically creating variable names like that: "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."
As you can read, the much better alternative is use one array and indexing. Indexing is simple, very efficient, neat, easy to read, easy to debug, etc, etc.
You can read more explanations and discussions here:
etc, etc,
0 Comments
See Also
Categories
Find more on Creating and Concatenating Matrices 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!