Changing the variable used in a loop
29 ビュー (過去 30 日間)
古いコメントを表示
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.
採用された回答
その他の回答 (1 件)
Steven Lord
2022 年 4 月 4 日
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))
参考
カテゴリ
Help Center および File Exchange で Loops and Conditional Statements についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!