Help with creating a function

조회 수: 3 (최근 30일)
Sarah Hicks
Sarah Hicks 2019년 3월 1일
답변: Image Analyst 2019년 3월 1일
Please write a MATLAB function with the following: (1) output a third-order polynomial function with the coefficients as the input variables; (2) Convert this function to function handle.
This is what I have but it will not work.
function output=poly3rd(a,s,d,f)
%this function creates a 3rd order polynomial with a,b,c, and d
%being the variables
output= a.*x.^3 +s.*x.^2 +d.*x+f
polynomial= @poly3rd;
end
poly3= @(x) *x.^3 +2.*x.^2+3.*x +4
  댓글 수: 2
dpb
dpb 2019년 3월 1일
function output=poly3rd(a,s,d,f)
%this function creates a 3rd order polynomial with a,b,c, and d
  1. Why do your variables not match the help text? Not your actual problem, but still...why not document what you write correctly?
  2. x isn't defined in the function
  3. Can't refer to the function you're defining inside the function itself even if were valid syntax and if both of those were ok, polynomial would still only be visible inside poly3rd
  4. Bad syntax for poly3--no coefficients in the expression
Walter Roberson
Walter Roberson 2019년 3월 1일
It is possible to refer to a function you are defining inside the function itself. It is done all the time for recursive functions.

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

채택된 답변

Image Analyst
Image Analyst 2019년 3월 1일
Close. But your poly3 needs to take the coefficients in as the input, NOT x. Try this:
poly3= @(a,s,d,f) poly3rd(a,s,d,f) % Define anonymous function
% Plot a function
y = poly3(1,2,3,4);
plot(y, 'b-');
grid on;
and the function pretty much like what you had but you needed to define some x.
function output = poly3rd(a,s,d,f)
%this function creates a 3rd order polynomial with a,b,c, and d
%being the variables
x = linspace(-10, 10, 500); % Whatever.
output = a.*x.^3 + s.*x.^2 + d.*x + f;
end
I second dpb's comment about making your comment and your variables match: either a,s,d,f OR a,b,c,d.

추가 답변 (0개)

카테고리

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