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

6 次查看(过去 30 天)
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 CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

标签

产品


版本

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by