フィルターのクリア

Filling a matrix with predefined expression for each element

1 回表示 (過去 30 日間)
Lorcan Conlon
Lorcan Conlon 2021 年 4 月 21 日
回答済み: Shivam 2023 年 10 月 11 日
I have a matrix which I wish to generate, adm the matrix is a function of the parameter alpha. It is a matrix with dimensions dim. I have an analytic expression for each element of the matrix. I wish to know what is the fastest way to populate this matrix in matlab. My code is
```
function [matout]=dipso(dim,alpha)
for kk=0:dim-1
for jj=0:dim-1
matout(kk+1,jj+1)=exp(-(abs(alpha))^2/2)*dispen(kk,jj,alpha);
end
end
function dispenout=dispen(m,n,x)
if m < n
dispenout=sqrt(factorial(m)/factorial(n))*((-conj(x))^(n-m)*laguerreL(m,n-m,abs(x)^2));
elseif m > n
dispenout=sqrt(factorial(n)/factorial(m))*((x)^(m-n)*laguerreL(n,m-n,abs(x)^2));
elseif m == n
dispenout=laguerreL(m,abs(x)^2);
end
```
However this is very slow. Is there a faster way I can populate the elements of my matrix?

回答 (1 件)

Shivam
Shivam 2023 年 10 月 11 日
Hi,
I understand you want to populate the matrix with faster execution than your existing code.
You can follow the below suggestions to make execution faster:
1. Preallocate the matrix:
matout = zeros(dim, dim);
2. Calculate exp(-abs(alpha)^2/2) outside the loop:
alpha_squared = abs(alpha)^2;
exp_alpha_squared = exp(-alpha_squared/2);
3. Precalculate factorials outside the loop and reuse them:
factorial_array = factorial(0:dim);
I hope it helps.

カテゴリ

Help Center および File ExchangeMultidimensional Arrays についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by