Changing the variable used in a loop

조회 수: 4 (최근 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 CenterFile Exchange에서 Loops 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