How to generate multi-dimensional matrix (3 dimension and above) without nested loops to reduce overall run time?
1 回表示 (過去 30 日間)
古いコメントを表示
My code contains a lot of multi-dimensional matrices (3 dim and above) which are increasing code complexity and run time. I want to replace nested loops with simple matrix multiplication to generate a 4-dimensional matrix as shown in the following code.
L=10; NF=512; Nr=4, Nt=4
for r=1:Nr
for t=1:Nt
h_T(:,:,r,t) = normrnd(0,sqrt(1/(2*2*L)),L,1)+1i*normrnd(0,sqrt(1/(2*2*L)),L,1);
h_F(:,:,r,t) = dft([h_T(:,:,r,t);zeros(NF-L,1)]);
end
end
%% the dft function is given as
function ft=dft(x)
N=length(x);
if size(x,2)~=1
x=x';
end
ft=sum(bsxfun(@times,x(1:N),exp(-2*pi*1i*([1:N]-1)'*([1:N]-1)/(8*N))),1)';
end
回答 (1 件)
Pavan Sahith
2024 年 2 月 16 日
Hello Sajid,
I observe that you're looking to optimize your MATLAB code by replacing nested loops with efficient matrix operations to generate a 4-dimensional matrix. In your DFT function , I assume that 'x' is a matrix where each column is a separate signal to transform.
You can utilize MATLAB's built-in functions and array operations to handle multi-dimensional matrices more efficiently.
Here's how you can achieve this while potentially reducing the runtime:
- Pre-allocate the matrices to avoid dynamic resizing during loop execution.
- Generate the complex Gaussian random variables for all 'r' and 't' values without loops.
- Reshape 'h_T' to a 2D matrix for Discrete Fourier Transform (DFT).
- Vectorize the DFT function to apply it to all columns of the input matrix.
L = 10; NF = 512; Nr = 4; Nt = 4;
% Pre-allocate h_T and h_F for efficiency
h_T = zeros(L, 1, Nr, Nt);
h_F = zeros(NF, 1, Nr, Nt);
% Generate the complex Gaussian random variables for all r and t at once
realPart = normrnd(0, sqrt(1/(2*2*L)), L, Nr, Nt);
imagPart = 1i * normrnd(0, sqrt(1/(2*2*L)), L, Nr, Nt);
h_T = realPart + imagPart;
%We reshape h_T to a 2D matrix, where each column represents a different combination of r and t.
% This allows us to apply the DFT to all columns simultaneously.
h_T_reshaped = reshape(h_T, L, Nr*Nt);
% Apply DFT to each column
h_F_reshaped = dft([h_T_reshaped; zeros(NF-L, Nr*Nt)]);
% Reshape the result back to a 4D matrix
h_F = reshape(h_F_reshaped, NF, 1, Nr, Nt);
%% Vectorized dft function
function ft = dft(x)
N = size(x, 1);
n = (0:N-1)';
k = n;
W = exp(-2 * pi * 1i * k * n' / (8 * N));
ft = W * x;
end
To know more about the 'reshape' function, you can refer to the following MathWorks documentation.
Hope this will help.
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Creating and Concatenating Matrices についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!