フィルターのクリア

How to assign a name for every result in every iteration by using for loop

8 ビュー (過去 30 日間)
Abdulrahman Alotibi
Abdulrahman Alotibi 2023 年 3 月 14 日
回答済み: Walter Roberson 2023 年 3 月 14 日
HI, in the following code:
T = 85;
Delta_T = 3;
for n = 1:15
T = T - Delta_T
end
How to assign a name for every result in every iteration by using for loop, i want the result for each iteration be like, T1=, T2=, T3=, ... T15=

回答 (2 件)

Jan
Jan 2023 年 3 月 14 日
This is a really bad idea. Hiding an index in the name of a variable is a complicated method, which requires even more complicated methods to access the variables later on. See TUTORIAL: Why and how to avoid Eval.
Prefer to use an index as index:
T0 = 85;
Delta_T = 3;
T = zeros(1, 5);
T(1) = T0;
for n = 2:15
T(n) = T(n - 1) - Delta_T;
end
Now use T(1) instead of T1.

Walter Roberson
Walter Roberson 2023 年 3 月 14 日
Compare:
T0 = 85;
Delta_T = 3;
n = 1;
start = tic;
while toc(start) < 20
eval(sprintf('T%d = T%d - Delta_T;', n, n-1));
n = n + 1;
end
variables = who();
size(variables)
ans = 1×2
61625 1
T = 85;
start = tic;
while toc(start) < 20
T(end+1) = T(end) - Delta_T;
end
size(T)
ans = 1×2
1 44186377
So even when growing an array using indexing is roughly 44186377/61625 which is about 700 times more efficient.
The efffciency for pre-allocating an array and using that array would be much higher still.

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

タグ

製品


リリース

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by