How can I avoid using for loop in this functions

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 件のコメント

Rik
Rik 2023 年 3 月 26 日
Have you tried logical indexing?
Dyuman Joshi
Dyuman Joshi 2023 年 3 月 26 日
編集済み: Dyuman Joshi 2023 年 3 月 26 日
Loops are quite efficient if used properly and the usage above looks good. Although you can club the 1st two conditions together -
if i~=0
k=abs(i);
y(i)=sign(i).^(k)./gamma(k+1).*(z/2).^k;
else
y(i)=-z.^2/4+1;
end
If you are dealing with floating point numbers, I would suggest you to use a tolerance to compare rather than equality.
As Rik mentions, logical indexing is another good option. If you can attach your data, we can run and test the code.
祥宇 崔
祥宇 崔 2023 年 3 月 26 日
@Dyuman Joshi Thanks! Guess the for loop is alright.
祥宇 崔
祥宇 崔 2023 年 3 月 26 日
@Rik Thanks! I will give it a try.

サインインしてコメントする。

 採用された回答

KSSV
KSSV 2023 年 3 月 26 日

1 投票

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

1 件のコメント

祥宇 崔
祥宇 崔 2023 年 4 月 11 日
Thanks! This is what I want!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

製品

リリース

R2020b

質問済み:

2023 年 3 月 26 日

コメント済み:

2023 年 4 月 11 日

Community Treasure Hunt

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

Start Hunting!

Translated by