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

9 visualizzazioni (ultimi 30 giorni)
Abdulrahman Alotibi il 14 Mar 2023
Risposto: Walter Roberson il 14 Mar 2023
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 CommentiMostra -2 commenti meno recentiNascondi -2 commenti meno recenti

Accedi per commentare.

### Risposte (2)

Jan il 14 Mar 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 CommentiMostra -2 commenti meno recentiNascondi -2 commenti meno recenti

Accedi per commentare.

Walter Roberson il 14 Mar 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)
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.
##### 0 CommentiMostra -2 commenti meno recentiNascondi -2 commenti meno recenti

Accedi per commentare.

### Categorie

Scopri di più su Matrix Indexing in Help Center e File Exchange

R2022b

### Community Treasure Hunt

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

Start Hunting!

Translated by