for loops out of bounds

2 vues (au cours des 30 derniers jours)
Vc27
Vc27 le 27 Déc 2022
Modifié(e) : Jan le 27 Déc 2022
I want to make an array with a list of values from 0 to pi in steps of 0.5, my code was
for loop i=0:0.5:pi;
i
end
when I do this i get a list of values but then when I type i, i only get the last value of the for loop, is there any way to get i to equal all the values separaelty? When i try and do i(2)/i(3) an error message comes up which says it is out of bounds ( assuming it thinks i only has 1 value), thanks in advance

Réponse acceptée

Jan
Jan le 27 Déc 2022
Modifié(e) : Jan le 27 Déc 2022
for loop i=0:0.5:pi;
This is no valid Matlab syntax. You can run code directly in the forum's interface and you will get an error message for this. A valid loop would be:
for i=0:0.5:pi
This creates i=0, i=0.5, ... iteratively. Of course all i are scalars - this is the purpose of a loop counter.
Your pseudo-code contains the solution of your problem already: Simply omit the for loop, but define the output directly:
i=0:0.5:pi;
Now you can access w.g. i(2) and i(3).
I suggest the free Matlab tutorial to learn such basics: https://www.mathworks.com/learn/tutorials/matlab-onramp.html

Plus de réponses (1)

the cyclist
the cyclist le 27 Déc 2022
i = 0:0.5:pi
i = 1×7
0 0.5000 1.0000 1.5000 2.0000 2.5000 3.0000
  1 commentaire
Vc27
Vc27 le 27 Déc 2022
I get an undefined error when I try this

Connectez-vous pour commenter.

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by