How can I avoid using for loop in this functions

1 次查看(过去 30 天)
This is the function whose speed I want to improve. I know I should use more matrix operation and use less for loop. But I have no idea how to use if-else in matrices.
function y=Besselj_approx(n,z)
y=zeros(1,length(n));
for i=n
if i>0
y(i)=1./gamma(i+1).*(z/2).^i;
elseif i<0
y(i)=(-1).^(-i)./gamma(-i+1).*(z/2).^(-i);
else
y(i)=-z.^2/4+1;
end
end
Any help is appreciated!
  4 个评论

请先登录,再进行评论。

采纳的回答

KSSV
KSSV 2023-3-26
function y=Besselj_approx(n,z)
i = n ;
y=zeros(1,length(n));
y(1:end)=-z.^2/4+1;
y(i>0) = 1./gamma(i(i>0)+1).*(z/2).^i(i>0);
y(i<0)=(-1).^(-i(i<0))./gamma(-i(i<0)+1).*(z/2).^(-i(i<0));

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

产品


版本

R2020b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by