creating matrices in a loop

1 次查看(过去 30 天)
vidyadhar k
vidyadhar k 2017-7-20
评论: Stephen23 2017-7-20
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 个评论
Stephen23
Stephen23 2017-7-20
"Can anyone help in this regard"
Yes, use indexing. Indexing is much better.

请先登录,再进行评论。

回答(1 个)

Stephen23
Stephen23 2017-7-20
编辑:Stephen23 2017-7-20
"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,

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by