Defining x as a symbol

조회 수: 9 (최근 30일)
Hannah
Hannah 2013년 11월 1일
답변: Image Analyst 2013년 11월 1일
Hi (:
This is my code. It calculates Simpson's rule The problem is that when I run it, it comes up with "Undefined function or variable 'x'" Now, I KNOW that I have to define x as a symbol, and have done so in my code, however I still get this error message. The only way my function works is if I define x as a symbol in the command window before running it.
How can I incorporate syms x into my function?
fun = a function
x0 = lower limit of integration
xn = upper limit of integration
n = steps
function result = simpson( fun,x0,xn,n )
%The function calculates an approximation for the integral using Simpson's
%rule.
syms x
f(x) = fun;
h = (xn-x0)/(n);
result = sum(f(x0)+f(xn));
for ii = x0+h:2*h:xn-h;
nresult = 4*f(ii);
result=sum(result+nresult);
end
for ii = x0+2*h:2*h:xn-h;
nresult = 2*f(ii);
result=sum(result+nresult);
end
result = (h/3)*result;
end

답변 (1개)

Image Analyst
Image Analyst 2013년 11월 1일
I'm not seeing it. Exactly where did you assign a value to x, such as
x = whatever;
It thinks f is an array and when you do f(x) it wants a number for x, which you have not assigned, so it can't get the x'th element of f so that's why it gives that error (which you actually forgot to post). Please post all the red text, don't just snip out a tiny portion of the error message and expect to get our best suggestions.

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by