Vector length error while using built-in function quad with diff

조회 수: 5 (최근 30일)
Ozan
Ozan 2012년 3월 24일
I tried to solve integral problem with built-in function quad. But I couldn't get the solution. The simplified version of my code is given below.
F=@(x)(diff(x).*diff(x)); Q = quad(F,-1,1)
But I have got the following error message;
??? Error using ==> quad at 80 The integrand function must return an output vector of the same length as the input vector.
Error in ==> Untitled at 3 Q = quad(F,-1,1)
I know that "diff" reduces the length of a vector by one, but I couldn't find way to solve this problem.
Thanks for your time.

채택된 답변

Jan
Jan 2012년 3월 24일
You can append a 0:
F = @(x)([0, diff(x) .* diff(x)]);
Q = quad(F, -1, 1)
Which effects does this have to the results?
Another idea:
F = @(x)(gradient(x) .* gradient(x));
Q = quad(F, -1, 1)
The result is slightly different.

추가 답변 (1개)

the cyclist
the cyclist 2012년 3월 24일
I am assuming that you are using "diff" inside your function F because it represent a numerical derivative of some kind. If that is the case, I recommend some caution, because simple differencing is not a very good way of doing that. I can make two related suggestions.
First, you could use the gradient() function instead of diff().
F=@(x)(gradient(x).*gradient(x));
Q = quad(F,-1,1)
[ Carefully read the documentation for gradient, as it makes different assumptions about the spacing of "x" that I am not 100% sure are what you need. ]
This should solve your length problem as well as being more numerically stable.
The second is to read this thread that discusses some of these issues. In particular, carefully read the posts from John D'Errico, a very knowledgeable user.

카테고리

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