In: Computer Science
Write a MATLAB function, called arbpoly, that computes a polynomial arbitrary nth degree. The function will take 2 inputs:
1) the first input will be a row vector, c, containing the coefficients of the polynomial, starting with the coefficient of the highest - degree term;
2) the second input will be a scalar, x, which is a real number at which the polynomial will be evaluated.
The function's only output, y, will be the scalar value of the polynomial computed at the value of input x.
In the body of your function, use vector(s), not loops, to evaluate the polynomial. MATLAB's function (length) will come in handy.
Note that script that calls/test the functions are already provided.
%script that calls/tests the function arbpoly
%tests 1-5 not random
c = [-2 0 3 -4 5 0 1];
x1 = -3;
z1 = arbpoly(c,x1)
c = [0 -3 1 4 0 1 -5];
x2 = 2;
z2 = arbpoly(c,x2)
c = [0 0 0 1];
x3 = -3;
z3 = arbpoly(c,x3)
c = [0 0];
x4 = 2;
z4 = arbpoly(c,x4)
c = [9 0 0 0];
x5 = 2;
z5 = arbpoly(c,x5)
%test with a ranom vector for c
len = randi([1 10],1,1);
c = randi([-10 10], 1, len);
x6 = 2;
z6 = arbpoly(c,x6)
%tests with random vector for c and x
c = randi([-10 10], 1, 5);
x7 = randi([-10 10], 1, 10);
z7 = zeros(1,10);
for i = 1:10
z7(i) = arbpoly(c,x7(i));
end
z7'
%%% this will plot the function
%%% uses a loop for x values
c = [-2 3 0 1];
x8 = linspace(-1.5,2.5,200);
z8 = zeros(1,200);
for i = 1:200
z8(i) = arbpoly(c,x8(i));
end
plot(x8,z8)
`Hey,
Note: If you have any queries related to the answer please do comment. I would be very happy to resolve all your queries.
clc
clear all
close all
format long
%tests 1-5 not random
c = [-2 0 3 -4 5 0 1];
x1 = -3;
z1 = arbpoly(c,x1)
c = [0 -3 1 4 0 1 -5];
x2 = 2;
z2 = arbpoly(c,x2)
c = [0 0 0 1];
x3 = -3;
z3 = arbpoly(c,x3)
c = [0 0];
x4 = 2;
z4 = arbpoly(c,x4)
c = [9 0 0 0];
x5 = 2;
z5 = arbpoly(c,x5)
%test with a ranom vector for c
len = randi([1 10],1,1);
c = randi([-10 10], 1, len);
x6 = 2;
z6 = arbpoly(c,x6)
%tests with random vector for c and x
c = randi([-10 10], 1, 5);
x7 = randi([-10 10], 1, 10);
z7 = zeros(1,10);
for i = 1:10
z7(i) = arbpoly(c,x7(i));
end
z7'
%%% this will plot the function
%%% uses a loop for x values
c = [-2 3 0 1];
x8 = linspace(-1.5,2.5,200);
z8 = zeros(1,200);
for i = 1:200
z8(i) = arbpoly(c,x8(i));
end
plot(x8,z8)
function z=arbpoly(c,x)
z=zeros(size(x));
for i=1:length(c)
z=z.*x+c(i);
end
end
Kindly revert for any queries
Thanks.