Effacer les filtres
Effacer les filtres

integral function gives the wrong answer

5 vues (au cours des 30 derniers jours)
Li Ea
Li Ea le 25 Juil 2022
Modifié(e) : Bruno Luong le 25 Juil 2022
Hello!
I meet some trouble when I use the function `integral`.
Such like the following code:
I = integral(@(X) myfun(X,4),0,2) % gives the right answer: 2
I = integral(@(X) myfun(X,4),2,4) % gives the right answer: 2
I = integral(@(X) myfun(X,4),0,4) % gives the wrong answer: 8
function value = myfun(x,L)
if x <= L/2
value = 4*x/L;
else
value = 4-4*x/L;
end
end

Réponse acceptée

Chunru
Chunru le 25 Juil 2022
Modifié(e) : Chunru le 25 Juil 2022
To define myfun, you need to ensure that it accept a vector argument x. The original code has problem when x is a vector (if x<L/2 when x is a vector). The following code gives correct answers:
subplot(131); fplot(@(X) myfun(X,4),[0,2])
subplot(132); fplot(@(X) myfun(X,4),[2,4])
subplot(133); fplot(@(X) myfun(X,4),[0,4])
I = integral(@(X) myfun(X,4),0,2) % gives the right answer: 2
I = 2.0000
I = integral(@(X) myfun(X,4),2,4) % gives the right answer: 2
I = 2
I = integral(@(X) myfun(X,4),0,4) % gives the wrong answer: 8
I = 4.0000
function value = myfun(x,L)
value = zeros(size(x));
idx = x <= L/2;
value(idx) = 4*x(idx)/L;
value(~idx) = 4-4*x(~idx)/L;
end

Plus de réponses (1)

Bruno Luong
Bruno Luong le 25 Juil 2022
Modifié(e) : Bruno Luong le 25 Juil 2022
The function need to be "vectorized", i.e. able to work on an input that is a vector when using with integral
I = integral(@(X) myfun(X,4),0,2) % gives the right answer: 2
I = 2.0000
I = integral(@(X) myfun(X,4),2,4) % gives the right answer: 2
I = 2
I = integral(@(X) myfun(X,4),0,4) % gives the wrong answer: 8
I = 4.0000
%
function value = myfun(x,L)
value = zeros(size(x));
left = x <= L/2;
value(left) = 4*x(left)/L;
value(~left) = 4-4*x(~left)/L;
end

Catégories

En savoir plus sur Partial Differential Equation Toolbox dans Help Center et File Exchange

Produits


Version

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by