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

5 visualizzazioni (ultimi 30 giorni)
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.

Risposta accettata

Jan
Jan il 24 Mar 2012
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.

Più risposte (1)

the cyclist
the cyclist il 24 Mar 2012
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.

Categorie

Scopri di più su Programming in Help Center e File Exchange

Tag

Community Treasure Hunt

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

Start Hunting!

Translated by