My piecewise function becomes NaN
3 次查看(过去 30 天)
显示 更早的评论
In the function below my integral becomes -inf when b is nonzero.
I think because of that my ans yields NaN instead of 2. How do I solve this problem?
Nz2=@(a,b) ((b==0)*integral(myfun,itta,inf)+(a>0 & b>0)*2)
Ans=Nz2(a,b)
4 个评论
Adam Danz
2019-9-1
See walter's answer to understand why you're getting a NaN and see his comment(s) under his answer.
采纳的回答
Walter Roberson
2019-8-31
You indicate that your integral becomes infinite when b is non-zero. You try to compensate for that by using (b==0) * integral() thinking that it will "select" the integral() calculation when b is 0 and thinking that otherwise it will skip it. But that is not what happens. When you calculate (b==0)*integral() then both sides are calculated no matter what the value of b is. When b is 0 then that is fine, as you get (0==0)*finite_value which is the finite_value. But when b is non-zero then you get (nonzero==0)*infinite_value which is 0*infinite_value which is NaN.
You cannot use the logical_condition*expression calculation form when the expression can be infinite or nan in any situation where the logical_condition is false.
To deal with this, you will either need to use the symbolic toolbox piecewise() function, or you will need to write a small function that uses if or logical indexing so that you do not calculate the integral in the b ~= 0 case.
3 个评论
Walter Roberson
2019-9-1
Nz2=piecewise( sym(t1n(j))>0 & sym(t1d(j))==0,integral(), sym(t1n(j))>0 & sym(t1d(j)) > 0, 1, 0);
The extra 0 is needed for the cast where t1n(j) <= 0 or t1n(j) < 0
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!