Changing the variable used in a loop

3 ビュー (過去 30 日間)
Toby Beisly
Toby Beisly 2022 年 4 月 4 日
コメント済み: Stephen23 2022 年 4 月 4 日
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.

採用された回答

VBBV
VBBV 2022 年 4 月 4 日
編集済み: VBBV 2022 年 4 月 4 日
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 件のコメント
Toby Beisly
Toby Beisly 2022 年 4 月 4 日
Oh this makes so much more sense than what I was tring to do, thanks for your answer :D

サインインしてコメントする。

その他の回答 (1 件)

Steven Lord
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_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 件のコメント
Toby Beisly
Toby Beisly 2022 年 4 月 4 日
Ahh I see having it as one variable makes way more sense now that I think about it, thanks for the help.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

製品


リリース

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by