Functions and For Loops For Polynomials

5 ビュー (過去 30 日間)
Alex Baham
Alex Baham 2020 年 3 月 31 日
コメント済み: Alex Baham 2020 年 3 月 31 日
I need to write a function that takes two inputs, a vector that is the the coefficients of a polynomial starting with the lowest degree term and a scalar to evaluate it at, I'm supposed to use a for loop to evaluate it in the function. I also cannot use '^' this built in function. Any guidance?
  2 件のコメント
James Tursa
James Tursa 2020 年 3 月 31 日
What have you done so far? What specific problems are you having with your code?
Alex Baham
Alex Baham 2020 年 3 月 31 日
This is what I have so far, but I'm not sure how much really needs to go in the for loop.
function y = arbpoly2(c,x)
n = length(c)-1;
r=n:-1:0;
for i=1:n
sum=0
sum=sum + c*x

サインインしてコメントする。

採用された回答

James Tursa
James Tursa 2020 年 3 月 31 日
Some guidance:
1) The sum=0 part needs to be moved outside the loop, prior to the loop starting. The way you have it the sum resets to 0 at each iteration.
2) Don't use "sum" as a variable name since that is an important existing MATLAB function name. Use something else, like "mysum" instead.
3) c is a vector of coefficients, so you should be indexing into c inside your loop. E.g., c(i)
4) The x needs to have an exponent applied to it based on the index i.
Make an attempt at these fixes and come back with any more problems you are having.
  1 件のコメント
Alex Baham
Alex Baham 2020 年 3 月 31 日
Will do. Thanks!

サインインしてコメントする。

その他の回答 (1 件)

David Hill
David Hill 2020 年 3 月 31 日
Too bad you can't use polyval(). This might get you started.
function e=evalPoly(p,a)
x=1;
e=0;
for k=1:length(p)
e=e+p(k)*x;
x=x*a;
end

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by