MATLAB: How to take the matrices stored in a loop one by one.

how to take stored matricesmatr

clear all
clc
D=20;
M=100;
K=40;
D_l=0.3;
for k=1:K
for d=1:D
tita(d)=randn(1,1);
tita_d=tita(d);
for m=1:M
a(m,d)=exp(j*2*pi*(m-1)*D_l*sin(tita_d));
end
end
A_k(:,:,k)=a.'/sqrt(D);
end
The problem in the above is: A_k stores all the values in loop K. Now I want to take each matrix of every loop k and write down into a big matrix. like A=[A_1 …. A_k],,,
How to do it, am struck here,, please help

Best Answer

  • Rather than doing this in loops, try this:
    D = 20;
    M = 100;
    K = 40;
    D_l = 0.3;
    tita_d = randn(D,1,K);
    A_k = bsxfun(@times, 0:M-1, sin(tita_d));
    A_k = exp(j*2*pi * D_l * A_k) / sqrt(D);
    It produces exactly the same output using vectorized code. You can reshape the output to be a matrix using this code:
    B_k = reshape(A_k,D,[]);