Filter löschen
Filter löschen

Changing the variable used in a loop

4 Ansichten (letzte 30 Tage)
Toby Beisly
Toby Beisly am 4 Apr. 2022
Kommentiert: Stephen23 am 4 Apr. 2022
Hey,
Im trying to write some looping code to make my life easier essentially what I've got is:
tube_inner_R = 0.003
tube_L1=12.14
tube_L2=6.46;
tube_L3=9.84;
tube_L4=8.17;
for inst = 1:4
tube_V=pi*tube_inner_R^2*tube_L(inst);
end
What I want is for each time the loop runs it uses the tube_L variable coresponding to that loop to be used to calculate the tube_V for that loop
Im really new to matlab but I have been looking around trying to find an answer and cant find anything that I can make sense of so any help would be appreciated, cheers.

Akzeptierte Antwort

VBBV
VBBV am 4 Apr. 2022
Bearbeitet: VBBV am 4 Apr. 2022
tube_inner_R = 0.003
tube_inner_R = 0.0030
tube_L=[12.14 6.46 9.84 8.17]; % put them in vector
for inst = 1:4
tube_V(inst)=pi*tube_inner_R^2*tube_L(inst); % access corresponding element
end
tube_V
tube_V = 1×4
1.0e-03 * 0.3433 0.1827 0.2782 0.2310
  1 Kommentar
Toby Beisly
Toby Beisly am 4 Apr. 2022
Oh this makes so much more sense than what I was tring to do, thanks for your answer :D

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Steven Lord
Steven Lord am 4 Apr. 2022
Can you iterate over numbered variables like tube_L1, tube_L2, tube_L3, etc? Yes.
Should you do this? The general consensus is no. See that Answers post for an explanation and alternatives.
In this case, you don't need the loop if you operate on the whole vector at once.
tube_inner_R = 0.003
tube_inner_R = 0.0030
tube_L = [12.14, 6.46, 9.84, 8.17]
tube_L = 1×4
12.1400 6.4600 9.8400 8.1700
tube_V = pi*tube_inner_R^2*tube_L
tube_V = 1×4
1.0e-03 * 0.3433 0.1827 0.2782 0.2310
Wherever you would have used (for example) tube_L3 and tube_V3 (as I'm guessing you would have continued the naming system) instead use tube_L(3) and tube_V(3).
fprintf("For L = %g, V is %g.\n", tube_L(3), tube_V(3))
For L = 9.84, V is 0.000278219.
  1 Kommentar
Toby Beisly
Toby Beisly am 4 Apr. 2022
Ahh I see having it as one variable makes way more sense now that I think about it, thanks for the help.

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Produkte


Version

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by