Plotting with a for loop

I am trying to plot this equation with for loop for x values between -3 and 6; y = x^4 - 4*x^3 - 6*x^2 + 15.
I am including the code and the plot that I get, why is my plot looking like this and how can I fix it?
for i = 1:10
x(i)= i-4;
y(i) = (i-4)^4 - 4*(i-4)^3 - 6*(i-4)^2 + 15;
end
plot(x,y)

5 Comments

i think you have extra values of x and y that are not 'in the loop'.
try
plot(x(1:10),y(1:10))
fyi, matlab is 'built' to do this kind of thing without any explicit loops:
x = -3:6; % or -3:0.5:6 if you want half-integer steps between points
y = x.^4 - 4.*x.^3 - 6.*x.^2 + 15;
plot(x,y)
you need the extra '.' in multiplication and exponentiation to tell matlab to perform the operations element-wise on the vector.
@Jussupj: you should move that to the answer section, because counting the points in the graph a missing pre-allocation is indeed causing this.
(and you would also need the dot for the division operation)
Thank you, both ways work, adding the '.' in multiplicatin and exponentiation is very useful.
Also I cleared the workspace and that worked as well.
At the beginning of every script you should always put "clear;close;clc" to get rid of variables and such when you run things.
If you add more points your graph would also look smoother and more like the equation.
You should not use them as a habit. During debugging it is a good idea (especially clear), but you should always keep thinking.
  • only use clc if you are printing things to the command window
  • only use clear (or clearvars) if you are not preallocating all your variables
  • only use close if you are actually opening new figures

Sign in to comment.

Answers (0)

Categories

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

Asked:

on 7 May 2020

Commented:

Rik
on 9 May 2020

Community Treasure Hunt

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

Start Hunting!