Integrating a multivariable function defined with logical operation

I have defined a multivariable function in Matlab as:
function f=test(x,y)
if x>=0 && y>0
f=x+y;
end
if x<0 && y>0
f=-x+y;
end
end
Now I want to integrate the function over x but with y fixed to be 1, so in the command window I wrote:
f=@(x) test(x,1);
integrate(f,-1,1)
Then I got an error saying:
Operands to the || and && operators must be convertible to logical scalar values.
Error in test (line 3)
if x>=0 && y>0
If I replace all && by & with everything else unchanged, there is another error:
Output argument "f" (and maybe others) not assigned during call to "test".
Error in @(x)test(x,1)
I appreciate if someone can help me do this integral numerically.
By the way, I noticed the problems appearing here seem to be unique when in the definition of the function there is some logical operation. If I defined
function f=test(x,y)
f=x+y;
end
and do the integral as before
f=@(x) test(x,1);
integral(f,-1,1)
It correctly returns 2.

 채택된 답변

Andrei Bobrov
Andrei Bobrov 2016년 6월 14일
편집: Andrei Bobrov 2016년 6월 14일
function f=test(x,y)
if x>=0 && y>0
f=x+y;
end
if x<0 && y>0
f=-x+y;
end
end
>>f=@(x) test(x,1);
>>integral(f,-1,1,'ArrayValued',true)

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Numerical Integration and Differentiation에 대해 자세히 알아보기

질문:

2016년 6월 14일

편집:

2016년 6월 14일

Community Treasure Hunt

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

Start Hunting!

Translated by