Plotting the third and firth order polynomial of a function?

조회 수: 1 (최근 30일)
Matt Amador
Matt Amador 2017년 10월 20일
댓글: Image Analyst 2017년 10월 21일
Hello, I have some trouble with my code. The objective of it is to fit the following data using a third and fifth order polynomial and plot the fits over the range 0<=t<=10
Data: >>t = 0:10;
>> y = [0 0.5104 0.3345 0.0315 -0.1024 -0.0787 ...
-0.0139 0.0198 0.0181 1.0046 -0.0037];
All of this data comes from the function: y(t) = e^(-0.5*t) * sin(t)
Here is my code so far:
clc
clear
t = 0:10;
y = exp(-0.5.*t)*sin(t);
p1 = polyfit(t,y,3);
p2 = polyfit(t,y,5);
plot(p1)
hold on
plot(p2)
grid on
I'm getting an error saying that the inner matrix dimensions must agree. Can anyone help out?
  댓글 수: 1
Jan
Jan 2017년 10월 20일
Please do not write a shortened rephrased error message, but a complete copy.

댓글을 달려면 로그인하십시오.

답변 (1개)

Jan
Jan 2017년 10월 20일
t = 0:10;
y = exp(-0.5 .* t) .* sin(t); % Elementwise .* instead of matrix multiplication *
Read the documentation of polyfit. You will find out, that the coefficients of the polynomial are replied. It is not meaningful to plot them. But polyval let you obtain the curves again. Use a finer grid then, e.g. tt = 0:0.1:10.
  댓글 수: 5
Jan
Jan 2017년 10월 21일
@Image Analyst: You mean "polyval", not "polyfit".
@Matt Amador: I assumed, that this is a homework and did not post a working solution. If this assumption was wrong: Sorry, I did not want to conceal the solution, but to let you the chance to solve it by your own.
Image Analyst
Image Analyst 2017년 10월 21일
Jan, right - polyval (right in the code, wrong in the description - sorry).
Matt, if someone posts homework, the expectation is that they label it as homework so people don't give a complete solution, lest they get caught for plagiarism and get in trouble. However, I gave you partial code based on your original code (plus a few other fancy things) so it might be okay. But if it's homework, the safest thing to do is to label it as homework. We wouldn't want you to get in trouble.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Polynomials에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by