How to assign a name for every result in every iteration by using for loop
9 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
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=
0 comentarios
Respuestas (2)
Jan
el 14 de Mzo. de 2023
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.
0 comentarios
Walter Roberson
el 14 de Mzo. de 2023
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)
T = 85;
start = tic;
while toc(start) < 20
T(end+1) = T(end) - Delta_T;
end
size(T)
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.
0 comentarios
Ver también
Categorías
Más información sobre Loops and Conditional Statements en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!