Azzera filtri
Azzera filtri

Filling a matrix with predefined expression for each element

1 visualizzazione (ultimi 30 giorni)
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?

Risposte (1)

Shivam
Shivam il 11 Ott 2023
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.

Categorie

Scopri di più su Multidimensional Arrays in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by