Filling a matrix with predefined expression for each element
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
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?
0 Kommentare
Antworten (1)
Shivam
am 11 Okt. 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.
0 Kommentare
Siehe auch
Kategorien
Mehr zu Multidimensional Arrays finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!