フィルターのクリア

Creating 'n' matrices with each one with 'n' in its name

3 ビュー (過去 30 日間)
Paul Barrette
Paul Barrette 2023 年 9 月 17 日
編集済み: Paul Barrette 2023 年 9 月 20 日
I am building 'n' matrices line by line:
YEAR1 = zeros(DATE_RANGE(1,3));
YEAR2 = zeros(DATE_RANGE(2,3));
YEAR3 = zeros(DATE_RANGE(3,3));
...
To avoid manually entering each line, I would like to use a looping method, e.g.,
for n=1:10
YEARn = zeros(DATE_RANGE(n,3));
end
My searches bring me to the concept of 'dynamic access' (eval), which is not recommended. But am not sure if this applies to my case.
  1 件のコメント
Stephen23
Stephen23 2023 年 9 月 18 日
編集済み: Stephen23 2023 年 9 月 20 日
"To avoid manually entering each line, I would like to use a looping method"
That is a good approach. The best approach is to use arrays.
"My searches bring me to the concept of 'dynamic access' (eval)"
That is a very bad approach.
"But am not sure if this applies to my case."
That advice definitely applies to your case. Your approach using dynamic variable names is not recommended: your approach forces you into writing slow, complex, inefficient, obfuscated, buggy code that is hard to debug:
So far there is no obvious reason why you could not just use basic matrices or arrays for your data, just like MATLAB is designed for. If all of those arrays are the same size then a basic 3D array would suffice.
Note that calling ZEROS with one input argument often produces unexpected results.

サインインしてコメントする。

採用された回答

Torsten
Torsten 2023 年 9 月 17 日
移動済み: Torsten 2023 年 9 月 17 日
YEAR{n} = zeros(DATE_RANGE(n,3));
  2 件のコメント
Dyuman Joshi
Dyuman Joshi 2023 年 9 月 17 日
That is, using Cell arrays to store matrices of different sizes.
@Paul Barrette, Using Cell arrays is also the first alternative mentioned in the thread you have linked -
Paul Barrette
Paul Barrette 2023 年 9 月 20 日
編集済み: Paul Barrette 2023 年 9 月 20 日
A 3D array, as suggested by @Stephen23, was my first idea, but the arrays are of slightly different size. Cell arrays is the way to go - I've never used them, but now is the time. Thanks all. And sorry for not searching better and not providing adequate explanations (I wil do better next time).

サインインしてコメントする。

その他の回答 (1 件)

Walter Roberson
Walter Roberson 2023 年 9 月 17 日
See https://www.mathworks.com/matlabcentral/answers/2020976-i-want-to-store-the-vector-from-each-for-loop-iteration-how-can-i-do-this#answer_1310391 for sample code that iterates through variable names, a, b, c, d, e, ... z, aa, ab, ac, ...

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

製品


リリース

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by