How to Correctly Plot Polynomial Functions in MATLAB?

Click For Summary
SUMMARY

This discussion focuses on correctly plotting polynomial functions in MATLAB, specifically the expression (x-4)(x-5)(x-6). The initial attempt using standard multiplication resulted in an error due to matrix dimension mismatch. The correct approach involves using element-wise multiplication with the dot operator, as demonstrated by the corrected code: y = (x-4).*(x-5).*(x-6). Additionally, it is recommended to avoid step sizes that are multiples of 0.1 to minimize numerical errors in simulations.

PREREQUISITES
  • Familiarity with MATLAB syntax and operations
  • Understanding of element-wise operations in MATLAB
  • Basic knowledge of polynomial functions
  • Awareness of numerical precision issues in computing
NEXT STEPS
  • Learn about MATLAB element-wise operations and their syntax
  • Explore best practices for numerical precision in MATLAB
  • Investigate polynomial function plotting techniques in MATLAB
  • Study the impact of step sizes on numerical simulations in programming
USEFUL FOR

This discussion is beneficial for MATLAB users, particularly students and professionals in engineering and data analysis, who are looking to accurately plot polynomial functions and understand numerical precision in their computations.

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 ·
Replies
10
Views
2K
Replies
7
Views
3K
  • · Replies 1 ·
Replies
1
Views
3K
  • · Replies 1 ·
Replies
1
Views
2K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 7 ·
Replies
7
Views
2K
  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 0 ·
Replies
0
Views
2K
  • · Replies 3 ·
Replies
3
Views
3K