integral function gives the wrong answer

3 visualizzazioni (ultimi 30 giorni)
Li Ea
Li Ea il 25 Lug 2022
Modificato: Bruno Luong il 25 Lug 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

Risposta accettata

Chunru
Chunru il 25 Lug 2022
Modificato: Chunru il 25 Lug 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

Più risposte (1)

Bruno Luong
Bruno Luong il 25 Lug 2022
Modificato: Bruno Luong il 25 Lug 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

Categorie

Scopri di più su Partial Differential Equation Toolbox in Help Center e File Exchange

Prodotti


Release

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by