How to Correctly Plot Polynomial Functions in MATLAB?

AI Thread Summary
To correctly plot polynomial functions in MATLAB, use element-wise operations by applying the dot operator, as in y = (x-4).*(x-5).*(x-6). The error encountered arises from using the standard multiplication operator, which is intended for matrix operations. It is advisable to choose step sizes that are not multiples of 0.1 to avoid approximation errors in binary computation. For better practice, define parameters like start and end points and the number of data points as variables for easier adjustments. Following these guidelines will ensure accurate polynomial plots in MATLAB.
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:

Similar threads

Replies
10
Views
2K
Replies
1
Views
2K
Replies
3
Views
1K
Replies
7
Views
1K
Replies
0
Views
1K
Replies
3
Views
2K
Replies
10
Views
1K
Back
Top