Increase time with for loop

2 vues (au cours des 30 derniers jours)
Cam B
Cam B le 5 Avr 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

Réponse acceptée

C B
C B le 5 Avr 2022
Modifié(e) : C B le 5 Avr 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 commentaires
Cam B
Cam B le 5 Avr 2022
Can the answer also be represented as a vector? Can you show both forms please. Thank you.
Walter Roberson
Walter Roberson le 5 Avr 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

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Matrix Indexing dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by