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 日

0 投票

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 件)

カテゴリ

質問済み:

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