for loops out of bounds

2 views (last 30 days)
Vc27
Vc27 on 27 Dec 2022
Edited: Jan on 27 Dec 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

Accepted Answer

Jan
Jan on 27 Dec 2022
Edited: Jan on 27 Dec 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

More Answers (1)

the cyclist
the cyclist on 27 Dec 2022
i = 0:0.5:pi
i = 1×7
0 0.5000 1.0000 1.5000 2.0000 2.5000 3.0000
  1 Comment
Vc27
Vc27 on 27 Dec 2022
I get an undefined error when I try this

Sign in to comment.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!