Matlab built-in function with argument conditions

people,

I am wondering if the following r function can be written as a built-in function in matlab. I tried to include the condition as a separate factor such as * (r> a) and I got NaN due to division 1 / r ^ 3 when r is 0.

function of r

+3


source to share


3 answers


I could make a simple way out. This is basically what Shai and Jigg suggested, i.e. Using an additional multiplicative factor (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


source


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.

+2


source


You may 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);

      

0


source







All Articles