Defining x as a symbol

10 vues (au cours des 30 derniers jours)
Hannah
Hannah le 1 Nov 2013
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

Réponses (1)

Image Analyst
Image Analyst le 1 Nov 2013
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.

Catégories

En savoir plus sur Programming dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by