0% found this document useful (0 votes)
14 views11 pages

A 8 R (ssr)

The document outlines three assignments involving curve fitting using MATLAB. The first assignment fits a cubic polynomial to a set of data points, while the second fits a logarithmic model to another dataset, suggesting an exponential relationship. The third assignment analyzes COVID-19 infection data in India, fitting polynomials of varying degrees to predict future cases and assess error reduction.

Uploaded by

Shubham Yadav
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views11 pages

A 8 R (ssr)

The document outlines three assignments involving curve fitting using MATLAB. The first assignment fits a cubic polynomial to a set of data points, while the second fits a logarithmic model to another dataset, suggesting an exponential relationship. The third assignment analyzes COVID-19 infection data in India, fitting polynomials of varying degrees to predict future cases and assess error reduction.

Uploaded by

Shubham Yadav
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Assignment No.

8: Curve fitting

Q.1. Determine an equation that can be fitted to the data using curve fitting
x=[ 0.9 1.5 3 4 6 8 9.5 ];
y=[ 0.9 1.5 2.5 5.1 4.5 4.9 6.3];
Solution: x=[ 0.9 1.5 3 4 6 8 9.5 ];
y=[ 0.9 1.5 2.5 5.1 4.5 4.9 6.3];
p=polyfit(x,y,3)
xp=0.9:0.1:9.5;
yp=polyval(p,xp);
plot(x, y, "o", xp, yp)
xlabel(‘x’); ylabel(‘y’)
Syntax
x=[ 0.9 1.5 3 4 6 8 9.5 ];
y=[ 0.9 1.5 2.5 5.1 4.5 4.9 6.3];
p=polyfit(x,y,3);
xp=0.9:0.1:9.5;
yp=polyval(p,xp);
plot(x, y, "o", xp, yp)
xlabel('x'); ylabel('y')
AND
close all
x=[0.9 1.5 3 4 6 8 9.5];
y=[0.9 1.5 2.5 5.1 4.5 4.9 6.3];
p=polyfit(x,y,3);
figure (1);
subplot(1,2,1)
plot(x,y,'s')
xp = 0.9:0.1:9.5;
yp=polyval(p,xp);
hold on
grid on
subplot(1,2,2)
plot(xp,yp,'b')
hold on
grid on
xlable('x'); ylable('y');

SURESH SINGH R. (23ME36) Page | 51


Result

AND

Explanation
• p = polyfit(x, y, 3): This line uses the polyfit function in MATLAB. polyfit finds
the coefficients of a polynomial that best fits the given data. Here, it's fitting a 3rd-
degree polynomial to the x and y data. The coefficients of the polynomial are
stored in the variable p.
• xp = 0.9:0.1:9.5;: This creates a vector xp containing x-values from 0.9 to 9.5
with a step of 0.1. This is used to generate a smoother curve for plotting.

SURESH SINGH R. (23ME36) Page | 52


• yp = polyval(p, xp);: This line uses the polyval function to evaluate the
polynomial (whose coefficients are in p) at the xp values. The resulting y-values
are stored in yp.
• plot(x, y, "o", xp, yp): This plots the data points as circles ("o") and the fitted
polynomial curve.
• xlabel('x'); ylabel('y'): These lines label the x-axis as "x" and the y-axis as "y"
on the plot.
AND
• close all: This command closes all open figures in MATLAB. It's useful to start
with a clean slate, ensuring that previous plots don't interfere with the new one.
• x = [0.9 1.5 3 4 6 8 9.5];: This line creates a vector named x containing the
given x-coordinates of the data points.
• y = [0.9 1.5 2.5 5.1 4.5 4.9 6.3];: This line creates a vector named y containing
the corresponding y-coordinates of the data points.
• p = polyfit(x, y, 3);: This is the core of the curve fitting.
o polyfit is a MATLAB function that finds the coefficients of a polynomial that
best fits a set of data points.
o The first two arguments, x and y, are the vectors of x-coordinates and y-
coordinates of the data.
o The third argument, 3, specifies the degree of the polynomial to fit (a cubic
polynomial in this case).
o The function returns a vector p containing the polynomial coefficients, in
descending order of power.

• figure(1);: This command opens a new figure window or makes figure number
1 the active figure. If a figure 1 already exists, it will be brought to the front.
This is where the plots will be displayed.

• subplot(1, 2, 1): This command divides the figure window into a 1-by-2 grid of
subplots and selects the first subplot for plotting. The arguments mean:

o 1: 1 row of subplots
o 2: 2 columns of subplots
o 1: Select the first subplot (left one)

• plot(x, y, 's'): This plots the original data points.

o x and y provide the coordinates.


o 's' specifies that the data points should be marked with squares.

SURESH SINGH R. (23ME36) Page | 53


• xp = 0.9:0.1:9.5; This creates a vector starting from 0.9, incrementing by 0.1,
and ending at 9.5. This is used to generate a smoother curve for the fitted
polynomial. The :20 is incorrect and would extend the x-range unnecessarily.
• yp = polyval(p, xp);: This calculates the y-values of the fitted polynomial at the
xp points.

o polyval evaluates the polynomial whose coefficients are in p at each x-value


in xp.

• hold on: This command keeps the current plot in the subplot so that subsequent
plotting commands will add to the same plot. This is important if you want to
plot both the original data and the fitted curve on the same axes.
• grid on: This turns on the grid lines in the subplot, making it easier to read
values from the plot.

• subplot(1, 2, 2): This selects the second subplot (the right one) in the 1-by-2
grid for plotting.

• plot(xp, yp, 'b'): This plots the fitted polynomial curve.

o xp and yp are the x and y values of the curve.


o 'b' specifies that the curve should be a blue line.

• hold on: Again, keeps the plot so far in the subplot and adds to it.
• grid on: Turns on the grid lines for this subplot.
• xlabel('x'); ylabel('y');: These commands label the x-axis as "x" and the y-axis
as "y". Note the correct spelling is xlabel and ylabel. It's likely that only the
second subplot will show these labels. To label both, you'd need these
commands inside each subplot section.

➢ The core idea is to find a polynomial function that approximates the relationship
between the x and y data points. polyfit does this by minimizing the sum of the
squared errors between the polynomial and the actual data points. A 3rd-degree
polynomial is chosen in this solution, but you could experiment with other degrees.
polyval then allows you to evaluate that polynomial at any x-value to get the
corresponding y-value on the fitted curve.

SURESH SINGH R. (23ME36) Page | 54


Q.2. Determine an equation that can be fitted to the data using curve fitting
(log)
T 0.0 0.5 1.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5 5.0
W 6.00 4.83 3.70 3.15 2.41 1.83 1.49 1.21 0.96 0.73 0.64 3.5 4.0
Solution: t=[0.0 0.5 1.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5 5.0];
w=[6.00 4.83 3.70 3.15 2.41 1.83 1.49 1.21 0.96 0.73 0.64];
p=polyfit(t,log(w),1);
m=p(1);
b=exp(p(2));
tm=0:0.1:5;
wm=b*exp(m*tm);
plot(t,w,'o',tm,wm)
Syntax
t=[0.0 0.5 1.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5 5.0];
w=[6.00 4.83 3.70 3.15 2.41 1.83 1.49 1.21 0.96 0.73 0.64];
p=polyfit(t,log(w),1);
m=p(1);
b=exp(p(2));
tm=0:0.1:5;
wm=b*exp(m*tm);
plot(t,w,'o',tm,wm)
Result

SURESH SINGH R. (23ME36) Page | 55


Explanation

• t = [0.0 0.5 1.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5 5.0];
• w = [6.00 4.83 3.70 3.15 2.41 1.83 1.49 1.21 0.96 0.73 0.64];
• p = polyfit(t, log(w), 1);: This is the key step. Instead of fitting to w directly, it
fits to log(w). This is because the problem specifies fitting to the "log" of the data,
suggesting an exponential relationship. It fits a first-degree polynomial (a line) to
the t values and the natural logarithm of the w values.
• m = p(1);: Extracts the first coefficient from p, which represents the slope (m) of
the line fitted to the t and log(w) data.
• b = exp(p(2));: Extracts the second coefficient from p, which represents the y-
intercept of the line fitted to the t and log(w) data. It then calculates exp() of this
value to get b. Since we fitted to log(w), b represents the coefficient in the
exponential equation.
• tm = 0:0.1:5;: Creates a vector tm for plotting a smooth curve.
• wm = b * exp(m * tm);: This constructs the exponential equation: w = b * exp(m
* t), where 'b' is the coefficient and 'm' is the rate constant. It calculates the w
values (wm) based on the fitted parameters b and m and the tm values.
• plot(t, w, 'o', tm, wm);: Plots the original data points (t, w) and the fitted
exponential curve (tm, wm).
➢ This problem assumes an exponential relationship between T and W. By taking the
logarithm of W, the exponential relationship is transformed into a linear one (log(W)
= mt + log(b)). polyfit is then used to find the best-fit line for this transformed data.
Finally, the coefficients of the line are used to determine the parameters of the
original exponential equation.

SURESH SINGH R. (23ME36) Page | 56


Q.3. Curve fit of 1st-7th order of polynomial for COVID-19 in India since
March 2020 and predict the infection at the end December 2020. Also present
the possibility of errors while moving from lower order (1st) to higher order
(7th) polynomials. Possible outcomes:
a) Plot of actual data
b) Plot of fitted data 1st-7th degree polynomial on a single plot
c) Plot the error showing improvement in error reduction
d) Recommendation: Follow the ___polynomial.
Syntax
t = [1 2 3 4 5 6 7 8 9];
cases = [500 1500 7000 25000 45000 90000 180000 300000 500000];
figure; hold on;
colors = ['r', 'g', 'b', 'c', 'm', 'y', 'k'];
xp = linspace(min(t), 10, 100);
for n = 1:7
p = polyfit(t, cases, n);
yp = polyval(p, xp);
plot(xp, yp, colors(n), 'LineWidth', 1.5);
end
plot(t, cases, 'ko', 'MarkerSize', 7, 'MarkerFaceColor', 'k');
legend('1st-degree','2nd-degree','3rd-degree','4th-degree','5th-degree','6th-degree','7th-
degree','Actual Data', 'Location', [0.3 0.5 0.2 0.3], 'FontSize', 10);
xlabel('Months since March 2020'); ylabel('Infected Cases');
title('COVID-19 Curve Fitting: 1st-7th Degree Polynomials');
hold off;
error = zeros(1,7);
for n = 1:7
p = polyfit(t, cases, n);
predicted = polyval(p, t);
error(n) = sqrt(mean((cases - predicted).^2));
end
figure;
plot(1:7, error, 'o-k', 'LineWidth', 1.5, 'MarkerSize', 8, 'MarkerFaceColor', 'm');
xlabel('Polynomial Degree'); ylabel('RMSE');
title('Error Reduction Across Polynomial Degrees');
grid on;
best_p = polyfit(t, cases, 4);
dec_cases = polyval(best_p, 10);
fprintf('Predicted infections in Dec 2020: %f\n', dec_cases);

SURESH SINGH R. (23ME36) Page | 57


Result

➢ Predicted infections in Dec 2020: 784722.222222

SURESH SINGH R. (23ME36) Page | 58


Explanation
This question involves fitting 1st-7th degree polynomial models to COVID-19 infection data,
predicting December 2020 values, analyzing error trends, and recommending the most reliable model.
➢ Approach:
1. Fit Polynomial Models (1st-7th degree): Use MATLAB’s polyfit to model the trend.
2. Predict December 2020 Cases: Use the best-fit polynomial for forecasting.
3. Error Analysis: Evaluate Root Mean Squared Error (RMSE) across different polynomial
degrees.
4. Recommendations: Identify the optimal polynomial degree balancing accuracy and stability.

Step 1: Define the Data:


• t = [1 2 3 4 5 6 7 8 9];This creates a vector named t containing the values 1 through 9. These likely
represent months since March 2020 (i.e., 1 for March, 2 for April, and so on).
• cases = [500 1500 7000 25000 45000 90000 180000 300000 500000];This creates a vector named
cases containing the number of COVID-19 infection cases for each corresponding month in t.
These are example data values.

Step 2: Fit and Plot All Polynomials in a Single Plot:


• figure;This opens a new figure window. This is where the first plot will be displayed.
• hold on;This is important for plotting multiple graphs on the same set of axes. It tells MATLAB to
"hold" the current plot so that subsequent plot commands will add to the existing graph instead of
replacing it.
• colors = ['r', 'g', 'b', 'c', 'm', 'y', 'k'];This creates a character array named colors containing
abbreviations for different colors: 'r' (red), 'g' (green), 'b' (blue), 'c' (cyan), 'm' (magenta), 'y'
(yellow), and 'k' (black). These will be used to distinguish the polynomial curves.
• xp = linspace(min(t), 10, 100);This creates a vector named xp containing 100 evenly spaced
points between the minimum value of t (which is 1) and 10. This vector will be used to plot the
smooth polynomial curves, extending one month beyond the existing data to predict into December
2020.
• for n = 1:7 This starts a for loop that will iterate 7 times, with the loop variable n taking on the
values from 1 to 7. Each iteration will fit a polynomial of degree n to the data.
• p = polyfit(t, cases, n); Inside the loop, this uses the polyfit function to find the coefficients of the
polynomial of degree n that best fits the data points (t, cases) in the least-squares sense. The
coefficients are stored in the vector p.
• yp = polyval(p, xp); This uses the polyval function to evaluate the polynomial with coefficients p
at each point in the xp vector. The resulting y-values are stored in the yp vector. These are the y-
values for the smooth curve.
• plot(xp, yp, colors(n), 'LineWidth', 1.5); This plots the smooth curve (xp, yp) on the current
axes. The color of the line is determined by colors(n) (e.g., the first curve is red, the second is green,
etc.), and the line width is set to 1.5.
• end This line ends the for loop, so the code iterates for the next degree.
• plot(t, cases, 'ko', 'MarkerSize', 7, 'MarkerFaceColor', 'k'); This plots the original data points
(t, cases) as black circles ('ko'). The MarkerSize is set to 7, and the MarkerFaceColor is set to black
to fill the circles.
• legend('1st-degree','2nd-degree','3rd-degree','4th-degree','5th-degree','6th-degree','7th-
degree','Actual Data', 'Location', [0.3 0.5 0.2 0.3], 'FontSize', 10); This adds a legend to the
plot to label each curve and the original data points. The Location is specified as a normalized
position within the figure, and the FontSize is set to 10.

SURESH SINGH R. (23ME36) Page | 59


• xlabel('Months since March 2020'); ylabel('Infected Cases'); These add labels to the x-axis
and y-axis of the plot.
• title('COVID-19 Curve Fitting: 1st-7th Degree Polynomials'); This line sets the title of the plot.
• hold off; This releases the "hold" on the plot, so any subsequent plotting commands will create a
new plot instead of adding to the current one.

Step 3: Error Analysis (Separate Plot):


• error = zeros(1,7); This initializes a vector named error of size 1x7, filled with zeros. This vector
will store the Root Mean Squared Error (RMSE) for each polynomial degree.
• for n = 1:7 This starts another for loop that iterates from 1 to 7, again calculating the error for
each polynomial degree.
• p = polyfit(t, cases, n); Inside the loop, this line calculates the polynomial coefficients for
degree n.
• predicted = polyval(p, t); This calculates the predicted y-values using the polynomial coefficients
p at the original x-values t.
• error(n) = sqrt(mean((cases - predicted).^2)); This calculates the RMSE between the actual
cases and the predicted values and stores it in the error vector.
• end This ends the error calculation loop.
• figure; This opens a new figure window for the error plot.
• plot(1:7, error, 'o-k', 'LineWidth', 1.5, 'MarkerSize', 8, 'MarkerFaceColor', 'm');
This line plots the RMSE values. The x-axis represents the polynomial degree (1 to 7), and the y-axis
represents the corresponding RMSE. The plot style is set to black circles connected by lines ('o-k'),
with a line width of 1.5, marker size of 8, and magenta filled markers.
• xlabel('Polynomial Degree'); ylabel('RMSE'); These lines label the axes of the error plot.
• title('Error Reduction Across Polynomial Degrees'); This line sets the title of the error plot.
• grid on; This turns on the grid lines on the plot.

Step 4: Prediction for December 2020:


• best_p = polyfit(t, cases, 4); This calculates the polynomial coefficients for a 4th-degree
polynomial. It assumes that a 4th-degree polynomial might be a good fit (this could be based on
visual inspection of the first plot or analysis of the error plot).
• dec_cases = polyval(best_p, 10); This predicts the number of cases for t = 10 (representing
December 2020) using the 4th-degree polynomial.
• fprintf('Predicted infections in Dec 2020: %f\n', dec_cases); This line prints the predicted
number of infections for December 2020 to the command window.

➢ Key Findings:
1. Low-degree polynomials (1st, 2nd): Too simplistic, failing to capture trends.
2. Medium-degree polynomials (3rd-4th): Strike a balance between accuracy and stability.
3. High-degree polynomials (6th-7th): Fit existing data but risk overfitting, making predictions
unreliable.
4. Recommended Choice: A 4th-degree polynomial provides a stable forecast without excessive
fluctuation.

SURESH SINGH R. (23ME36) Page | 60


❖ Learning Outcomes:

This assignment focuses on curve fitting, which means finding the best
mathematical equation to represent a given set of data.
Here are the key learning outcomes:
1. Understanding Polynomial Curve Fitting: We'll learn how to fit
different-degree polynomials to data, using MATLAB's polyfit function.
2. Applying Logarithmic Curve Fitting: We explore how logarithmic
transformations help linearize exponential relationships for curve fitting.
3. Visualizing Data Trends: We'll gain experience in plotting and analyzing
fitted curves alongside actual data points using MATLAB functions like
plot() and xlabel().
4. Error Analysis and Model Selection: We study how moving from lower-
degree to higher-degree polynomials impacts error reduction, helping us
choose the best-fit model.
5. Predictive Modeling: The assignment includes forecasting future values
(such as COVID-19 infection rates) using polynomial models, providing
insights into predictive analytics.
6. Comparing Models for Stability and Accuracy: We assess different
polynomial degrees to understand when higher-order models lead to
overfitting.
By the end of this assignment, we should be able to confidently use
MATLAB for curve fitting, analyze trends, and make data-driven
predictions.

SURESH SINGH R. (23ME36) Page | 61

You might also like