Matlab plot not showing correct values

9 views (last 30 days)
Takura Nyatsuro
Takura Nyatsuro on 20 Oct 2022
Edited: dpb on 20 Oct 2022
Hi there,
Im trying to plot a graph using a for loop but the correct values are not being plotted. It is currently outputting the
same value 5 times. Any help would be appreciated.
clc;
clear;
hold on;
x=1:5;
grid on;
for i = 1:5
v=0.1553567*(i.^6)-2.0416*(i.^5)+9.1837*(i.^4)-14.829*(i.^3)-1.3703*(i.^2)+32.821*(i)-1.3155
end
plot(x,v,".")

Answers (2)

Torsten
Torsten on 20 Oct 2022
v(i)=0.1553567*(i.^6)-2.0416*(i.^5)+9.1837*(i.^4)-14.829*(i.^3)-1.3703*(i.^2)+32.821*(i)-1.3155
instead of
v=0.1553567*(i.^6)-2.0416*(i.^5)+9.1837*(i.^4)-14.829*(i.^3)-1.3703*(i.^2)+32.821*(i)-1.3155

dpb
dpb on 20 Oct 2022
Edited: dpb on 20 Oct 2022
No need for and don't use loops here...
p=[0.1553567,-2.0416,9.1837,-14.829,-1.3703,32.821,-1.3155]; % store poly coefficients as vector
x=1:5; % x range desired
y=polyval(p,x); % calculate y(p(x)) at x
plot(x,y,'*')
grid on;
Your problem above is you're calculating on value at a time in the loop, but not saving in an array and not plotting until after the loop has finished. Hence, the value is always the last iteration through the loop; you've written over the previous loop value each time the loop executes.

Categories

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

Community Treasure Hunt

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

Start Hunting!