Filter löschen
Filter löschen

How to generate multi-dimensional matrix (3 dimension and above) without nested loops to reduce overall run time?

1 Ansicht (letzte 30 Tage)
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)]);
%% the dft function is given as
function ft=dft(x)
if size(x,2)~=1

Antworten (1)

Pavan Sahith
Pavan Sahith am 16 Feb. 2024
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;
To know more about the 'reshape' function, you can refer to the following MathWorks documentation.
Hope this will help.


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!

Translated by