Changing the variable used in a loop
2 views (last 30 days)
Show older comments
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.
Accepted Answer
More Answers (1)
Steven Lord
on 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_L = [12.14, 6.46, 9.84, 8.17]
tube_V = pi*tube_inner_R^2*tube_L
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))
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!