Increase time with for loop

조회 수: 4 (최근 30일)
Cam B
Cam B 2022년 4월 5일
댓글: Walter Roberson 2022년 4월 5일
I am trying to create a variable x that increases by 0.5, 16 times. Thus, at i =16, x it should be 8. I keep running into an error of 'Index exceeds the number of array elements. Index must not exceed 1.'
x=[];
x(1)=0;
for i=1:14
x=x(i)+0.5
end

채택된 답변

Chetan Bhavsar
Chetan Bhavsar 2022년 4월 5일
편집: Chetan Bhavsar 2022년 4월 5일
You want like this or you want array?
x=0;
for i=1:16
x=x+0.5
end
x = 0.5000
x = 1
x = 1.5000
x = 2
x = 2.5000
x = 3
x = 3.5000
x = 4
x = 4.5000
x = 5
x = 5.5000
x = 6
x = 6.5000
x = 7
x = 7.5000
x = 8
y={};
x=0;
for i=1:16
x=x+0.5;
y = [y x];
end
y
y = 1×16 cell array
{[0.5000]} {[1]} {[1.5000]} {[2]} {[2.5000]} {[3]} {[3.5000]} {[4]} {[4.5000]} {[5]} {[5.5000]} {[6]} {[6.5000]} {[7]} {[7.5000]} {[8]}
  댓글 수: 3
Cam B
Cam B 2022년 4월 5일
Can the answer also be represented as a vector? Can you show both forms please. Thank you.
Walter Roberson
Walter Roberson 2022년 4월 5일
x(1)=0;
for i=1:16
x(i+1)=x(i)+0.5
end
x = 1×2
0 0.5000
x = 1×3
0 0.5000 1.0000
x = 1×4
0 0.5000 1.0000 1.5000
x = 1×5
0 0.5000 1.0000 1.5000 2.0000
x = 1×6
0 0.5000 1.0000 1.5000 2.0000 2.5000
x = 1×7
0 0.5000 1.0000 1.5000 2.0000 2.5000 3.0000
x = 1×8
0 0.5000 1.0000 1.5000 2.0000 2.5000 3.0000 3.5000
x = 1×9
0 0.5000 1.0000 1.5000 2.0000 2.5000 3.0000 3.5000 4.0000
x = 1×10
0 0.5000 1.0000 1.5000 2.0000 2.5000 3.0000 3.5000 4.0000 4.5000
x = 1×11
0 0.5000 1.0000 1.5000 2.0000 2.5000 3.0000 3.5000 4.0000 4.5000 5.0000
x = 1×12
0 0.5000 1.0000 1.5000 2.0000 2.5000 3.0000 3.5000 4.0000 4.5000 5.0000 5.5000
x = 1×13
0 0.5000 1.0000 1.5000 2.0000 2.5000 3.0000 3.5000 4.0000 4.5000 5.0000 5.5000 6.0000
x = 1×14
0 0.5000 1.0000 1.5000 2.0000 2.5000 3.0000 3.5000 4.0000 4.5000 5.0000 5.5000 6.0000 6.5000
x = 1×15
0 0.5000 1.0000 1.5000 2.0000 2.5000 3.0000 3.5000 4.0000 4.5000 5.0000 5.5000 6.0000 6.5000 7.0000
x = 1×16
0 0.5000 1.0000 1.5000 2.0000 2.5000 3.0000 3.5000 4.0000 4.5000 5.0000 5.5000 6.0000 6.5000 7.0000 7.5000
x = 1×17
0 0.5000 1.0000 1.5000 2.0000 2.5000 3.0000 3.5000 4.0000 4.5000 5.0000 5.5000 6.0000 6.5000 7.0000 7.5000 8.0000

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by