3
votes

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.

function of r

3
what is the value of a?Shai
a is a positive number, say 1.nos
Do you absolutely need it to be an inline function? Or can you simply get rid of the NaNs a posteriori with something like nu(isnan(nu))=0?Cape Code

3 Answers

2
votes

I fould a simple way out. It's basically what Shai and Jigg suggested, i.e. using an extra multiplicative factor of (r>a).

To get rid of NaN, we just need to add eps to the denominator of 1/r3, i.e.

 1/(r+eps)^3 *(r>a)
2
votes

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.

0
votes

You can try

chi = 1; %// arbitrary value
a = 1; %// arbitrary value
theta = pi/3; %// arbitrary value
nu = @( r ) (r>a).*( (chi/3).*((a.^3)./(r.^3)).*(3*cos(theta).^2 -1);