folks,
I am wondering if it is possible to write the following function of r as an inline function in matlab. I tried to include the condition as a separate factor such as *(r>a) and I got NaN due to the division of 1/r^3 when r is 0.
First, you haven't stated what should actually happen if r = 0
. Mathematically the term gets infinity. I assumed you rather want to set it to zero. And what should happen for r = a
? Just another ill-defined case, are you sure your formula is correct?
If you have the Statistics Toolbox you can use nansum
. If not, I'd say there is no way around to write your own function similar to nansum
, which can't be done inline.
r = -5:1:5;
a = 1;
R = 42; %// rest of your function
%// not working, or removing of nan afterwards required
X = @( r ) (r>=a).*(a./r).^3*R;
%// inline solution with statistics toolbox
Y = @( r ) arrayfun(@(x) nansum( (x>=a)*(a/x)^3*R ), r);
output = [X(r)' Y(r)']
nansum
is not vectorized, if you still want to use it for vectors wrap it into arrayfun.
The code of nansum
does exactly what was suggested in the comments (output(isnan(output))=0
), I'm probably not allowed to copy&paste it here. It filters out all NaN
and then sums the input. Use open nansum
to have insight.
As pointed out by Jigg, similar functions like nanmean
would do the trick as well.
a
? – Shainu(isnan(nu))=0
? – Cape Code