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

8 Ansichten (letzte 30 Tage)
Abdulrahman Alotibi am 14 Mär. 2023
Beantwortet: Walter Roberson am 14 Mär. 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 Kommentare-2 ältere Kommentare anzeigen-2 ältere Kommentare ausblenden

Melden Sie sich an, um zu kommentieren.

Antworten (2)

Jan am 14 Mär. 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 Kommentare-2 ältere Kommentare anzeigen-2 ältere Kommentare ausblenden

Melden Sie sich an, um zu kommentieren.

Walter Roberson am 14 Mär. 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 Kommentare-2 ältere Kommentare anzeigen-2 ältere Kommentare ausblenden

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by