How to Correctly Plot Polynomial Functions in MATLAB?

Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
1 reply · 2K views
eurekameh
Messages
209
Reaction score
0
How do I plot something like (x-4)(x-5)(x-6)?
I've tried:

x = -6:0.01:6;
y = (x-4)*(x-5)*(x-6);
plot(x,y)

It's giving me the error:

Error using *
Inner matrix dimensions must agree.
 
Physics news on Phys.org
Code:
y = (x-4).*(x-5).*(x-6);
The MATLAB "*" symbol is matrix multiplication.
If you want each element of a vector to be multiplied by the corresponding element of another vector, you have to "dot the star". Same if you want powers... v^2 is different from v.^2.

Aside: it is good form to choose step sizes that are not multiples of 0.1 ... try inverse powers of 2 instead.
The reason is that 0.1 is an irrational number in binary, so your computer has to approximate it ... when you, later, write simulations involving many iterations the errors can mount up.

Best practice: pick the number of data points you want first... in fact, put all your parameters in as variables: makes for easy adjustment later:
Code:
a=-6; # start
b=6; # finish
N=1024; # no. data points
dx=(b-a)/(N-1); # step size
x=a:dx:b; # x-axis
y=(x+1).*x;
 
Last edited: