Graphing a For Loop Array

124 vues (au cours des 30 derniers jours)
Owen McKim
Owen McKim le 9 Fév 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...

Réponses (1)

Turlough Hughes
Turlough Hughes le 9 Fév 2022
Modifié(e) : Turlough Hughes le 9 Fév 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)

Catégories

En savoir plus sur 2-D and 3-D Plots dans Help Center et File Exchange

Produits


Version

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by