Output doesn't seem to be correct

Hi so this is the polynomial question that I've been stuck on for a while, this is what I have so far but apparently my output is not correct.

6 Comments

this is what I have so far but apparently my output is not correct.
Looks fine for me.
The ultimate test would be
res = polyval(p,x) - y
which should come out to be approximately the zero vector.
I checked the output on my class website but it's not right.
Do not writematrix(ans) and instead writematrix(f1)
Sherman Ng
Sherman Ng on 15 Mar 2022
Edited: Sherman Ng on 15 Mar 2022
I used the code that you provided but apparently that didn't work either.
The question asks: Enter the polynomial coefficients (for degrees [9 8 7 "" 2 1 0]) as a vector and the y-values of the polynomial evaluated at x-values of [0 0.01 0.02 "" 0.98 0.99 1].
Yes, you only did it for degree 9.
Make a loop to get coefficients and values for the other degrees.
So something like this?
n=9
c = zeros(n,n+1);
for k = 1:n
syms x y
z(k) = (x+y)^k;
coeff = coeffs(z(k));
c(k,1:k+1) = double(coeff);
end

Sign in to comment.

Answers (1)

Hi Sherman,
I understand that you are trying to evaluate the coefficients for a polynomial of degree 9 that passes through the mentioned points. You also want to calculate the values of the polynomial at specific points.
This can be achieved using the “polyfit” function to fit the given values to a polynomial of the desired degree. This function fits a polynomial to the given data points using least squares regression. Afterwards, you can evaluate the polynomial at different points using the “polyval” function.
It can be done as follows:
% Given data points
x = [0, 0.1111, 0.2222, 0.3333, 0.4444, 0.5556, 0.6667, 0.7778, 0.8889, 1];
y = [0, 6.988, 5.1826, -3.1445, -7.5146, -2.4209, 5.7187, 6.6621, -0.7779, -7.2391];
% Degree of the polynomial
degree = 9;
% Fit the polynomial using polyfit
coefficients = polyfit(x, y, degree);
% Evaluate the polynomial at specified x-values
x_values = 0:0.01:1;
y_values = polyval(coefficients, x_values);
% Display the coefficients vector
coefficients_vector = coefficients'
% Display the x-y values as two rows of a matrix
xy_matrix = [x_values; y_values];
Further make sure answers are in the expected format that could also be a possible reason for the wrong submission.
Here are the links to the “polyfit” and “polyval” documentations, to learn more about them.
Hope this helps.
Thanks
Gyan

Categories

Tags

Asked:

on 15 Mar 2022

Answered:

on 16 Nov 2023

Community Treasure Hunt

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

Start Hunting!