Why wont my code plot anything

4 visualizzazioni (ultimi 30 giorni)
james Green
james Green il 23 Mar 2022
Commentato: Voss il 23 Mar 2022
clear
for n = 1:10
e = 1/factorial(n);
end
disp('calculated value for e = ')
disp(e)
percent_error = e/exp(1)*100
plot(1:10,e)

Risposta accettata

Voss
Voss il 23 Mar 2022
It doesn't appear to plot because e is a scalar. e is a scalar because it's overwritten each time through the loop.
Instead, make e a vector, one element of which is calculated each time through the loop. Then the plot will show up:
clear
for n = 1:10
% e = 1/factorial(n);
e(n) = 1/factorial(n);
end
disp('calculated value for e = ')
calculated value for e =
disp(e)
1.0000 0.5000 0.1667 0.0417 0.0083 0.0014 0.0002 0.0000 0.0000 0.0000
percent_error = e/exp(1)*100
percent_error = 1×10
36.7879 18.3940 6.1313 1.5328 0.3066 0.0511 0.0073 0.0009 0.0001 0.0000
plot(1:10,e)
  2 Commenti
james Green
james Green il 23 Mar 2022
thanks for the answer, i saw alot of people talking about scalers and vectors in similar questons but didnt understand how to make e a vector seems so simple now. thanks
Voss
Voss il 23 Mar 2022
You're welcome! Yep, it's easy when you know how.

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su MATLAB in Help Center e File Exchange

Tag

Community Treasure Hunt

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

Start Hunting!

Translated by