Matlab built-in function with argument conditions
First, you haven't specified what should 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 wrong case, are you sure your formula is correct?
If you have the Statistics Toolkit, you can use . If not, I would say that there is no way to write your own function like that that cannot be done inline. nansum
nansum
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 in arrayfun.
The code nansum
does exactly what was suggested in the comments ( output(isnan(output))=0
), maybe I am not allowed to copy and paste it here. It filters out everything NaN
and then sums up the input. Use open nansum
to have an idea.
As pointed out by Jigg, functions like nanmean
this will do the trick too.
source to share