# integral function gives the wrong answer

조회 수: 4 (최근 30일)
Li Ea 2022년 7월 25일
편집: Bruno Luong 2022년 7월 25일
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 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 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