필터 지우기
필터 지우기

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 CenterFile Exchange에서 Multidimensional Arrays에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by