Problem with integral() function
5 次查看(过去 30 天)
显示 更早的评论
I have a problem with the usage of the MatLab build-in integral function and I cannot understand the essence of it. Below I am attaching the things that might be the cause of a given problem. I have also implemented the Trapezoidal and the Simson's rules and they work completly fine, so that is the thing that makes me even more confused as I guess there should not be a problem with the 'f' function.
cheby1 - function that generates Chebyshev polynomials of the first order
fibonacci - my own function that generates the Fibonacci sequence
MATLAB version - R2018b
main.m
n = -1;
while(n <= 0)
n = input('Enter the n number: ');
end
fib = fibonacci(n);
fun = @(x) f(n,x,fib);
fx = f(n,x,fib);
disp('Simpson:')
S = simpson(0,4,0.01,fun)
disp('Trapezoidal:')
T = trapezoidal(0,4,0.01,fun)
disp('MatLab build-in')
I = integral(fun,0,4)
chey1.m
function T = cheby1(x, N)
if N == 1
T(N) = x;
else
T(1) = x;
T(2) = 2*x^2-1;
for i = 3:N
T(i) = 2*x*T(i-1)-T(i-2);
end
end
end
f.m - function that generates f(x) of the form
where
is the Chebyshev polynomial
function S = f(n,x,fib)
S = 0;
T = cheby1(x, n);
for i=1:n
S = S + T(i) * fib(i);
end
end
The erros I get:

0 个评论
采纳的回答
Steven Lord
2019-5-28
Star Strider is correct. Your f function does not satisfy the requirements imposed upon integrand functions by integral. From the integral documentation page:
"For scalar-valued problems, the function y = fun(x) must accept a vector argument, x, and return a vector result, y. This generally means that fun must use array operators instead of matrix operators. For example, use .* (times) rather than * (mtimes). If you set the 'ArrayValued' option to true, then fun must accept a scalar and return an array of fixed size."
Your function cannot accept a vector argument for x. Either modify it so it can (the easiest way to do so would probably be to use a for loop to iterate over the elements of x and compute the value of the integrand for each of those elements in turn) or specify the 'ArrayValued' option in your integral call.
更多回答(1 个)
Star Strider
2019-5-28
Your post lacks details. However, Iit seems that ‘x’ is a vector. It is not possible to assign a vector to a scalar array element.
Try this:
function T = cheby1(x, N)
if N == 1
T(N) = x;
else
T(1) = x(1);
T(2) = 2*x(2)^2-1;
for i = 3:N
T(i) = 2*x(i)*T(i-1)-T(i-2);
end
end
end
That may not be the only error. If I guess correctly, it should prevent the error you posted.
另请参阅
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!