integral function gives the wrong answer

3 visualizaciones (últimos 30 días)
Li Ea
Li Ea el 25 de Jul. de 2022
Editada: Bruno Luong el 25 de Jul. de 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

Respuesta aceptada

Chunru
Chunru el 25 de Jul. de 2022
Editada: Chunru el 25 de Jul. de 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

Más respuestas (1)

Bruno Luong
Bruno Luong el 25 de Jul. de 2022
Editada: Bruno Luong el 25 de Jul. de 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

Categorías

Más información sobre Partial Differential Equation Toolbox en Help Center y File Exchange.

Etiquetas

Productos


Versión

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by