Increase time with for loop

1 view (last 30 days)
Cam B
Cam B on 5 Apr 2022
Commented: Walter Roberson on 5 Apr 2022
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

Accepted Answer

C B
C B on 5 Apr 2022
Edited: C B on 5 Apr 2022
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 Comments
Cam B
Cam B on 5 Apr 2022
Can the answer also be represented as a vector? Can you show both forms please. Thank you.
Walter Roberson
Walter Roberson on 5 Apr 2022
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

Sign in to comment.

More Answers (0)

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!