integral function gives the wrong answer

5 次查看(过去 30 天)
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

采纳的回答

Chunru
Chunru 2022-7-25
编辑:Chunru 2022-7-25
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

更多回答(1 个)

Bruno Luong
Bruno Luong 2022-7-25
编辑:Bruno Luong 2022-7-25
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

类别

Help CenterFile Exchange 中查找有关 Partial Differential Equation Toolbox 的更多信息

产品


版本

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by