Why wont my code plot anything

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)

 Accepted Answer

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 Comments

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
You're welcome! Yep, it's easy when you know how.

Sign in to comment.

More Answers (0)

Categories

Find more on MATLAB in Help Center and File Exchange

Tags

Asked:

on 23 Mar 2022

Commented:

on 23 Mar 2022

Community Treasure Hunt

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

Start Hunting!