Graphing a For Loop Array

209 views (last 30 days)
Owen McKim
Owen McKim on 9 Feb 2022
Edited: Turlough Hughes on 9 Feb 2022
for i = 0:5:100
y(i) = i
x(i) = i^2;
end
figure(1)
plot(y,x)
I just want to create a simple plot graph of an exponentional curve, from 0 to 100 with a step size of 5. However I'm getting an error "Array indices must be positive integers or logical values" so I entere 1 instead of 0. This now works but it outputs 1,6,11... so on. Not starting from zero. This other issue I am having is my array places 0 between each value
"1 0 0 0 0 6 0 0 0 0 11 0 0 0 0 16 0 0 0 0 21 0 0 0 0 26"
How do I stop this? As this is affecting how my graph looks
I just want the array to output 1,6,11,16,21...

Answers (1)

Turlough Hughes
Turlough Hughes on 9 Feb 2022
Edited: Turlough Hughes on 9 Feb 2022
i can either be the index or a value that you use on the RHS of your equations but typically not both. To fix your code you could add a counter, c, for indexing the positions in x and y
c = 1;
for i = 0:5:100
x(c) = i;
y(c) = i^2;
c = c + 1;
end
figure()
plot(x,y)
Here are two other, preferable, ways you could plot it:
1.
figure(), fplot(@(x) x.^2, [0 100])
2.
x = 0:5:100;
y = x.^2;
figure(), plot(x,y)

Categories

Find more on Graph and Network Algorithms in Help Center and File Exchange

Products


Release

R2021a

Community Treasure Hunt

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

Start Hunting!