How to remove all for-loops with vectorization?

4 views (last 30 days)
I have the following piece of code. I have posted similar codes earlier also and therefore 1st I tried myself to vectorize it but coudn't succeed. How can we replace all for-loops by making it vectorized code?
u=[35 75 -35 -75 0.3 0.5];
b=u;
K=length(u)/3;% Constant1
u1=u(1:2*K);
alpha=u(2*K+1:end);
M = 10; % Consatn2
N = 6; % Consatn3
s1=zeros(M,K);
s2=zeros(N,K);
C=zeros(M*N, length(u1)-K);
%%%%%%%%%%%%%%%%%%%
% Xo Calculation
%%%%%%%%%%%%%%%%%%%
for i=1:K
for h=1:M
s1(h,i)=exp(j*2*pi*(h-1)*0.5*sind(u1(i)));
end
for p=1:N
s2(p,i)=exp(j*2*pi*(p-1)*0.5*sind(u1(K+i)));
end
end
for g= 1:K
C(:,g)=kron(s1(:,g),s2(:,g));
end
Xo=C*alpha';
%%%%%%%%%%%%%%%%%%%
% Xe Calculation
%%%%%%%%%%%%%%%%%%%
bu=b(1:2*K); alphab=b(2*K+1:end);
s1_e=zeros(M,K);
s2_e=zeros(N,K);
C_e=zeros(M*N, length(u1)-K);
for i=1:K
for h=1:M
s1_e(h,i)=exp(j*2*pi*(h-1)*0.5*sind(bu(i)));
end
for p=1:N
s2_e(p,i)=exp(j*2*pi*(p-1)*0.5*sind(bu(K+i)));
end
end
for g= 1:K
C_e(:,g)=kron(s1_e(:,g),s2_e(:,g));
end
Xe=C_e*alphab';
%%%%%%%%%%%%%%%%%%
% MSE
%%%%%%%%%%%%%%%%%%
e=0.0;
for s=1:M*N
e=e+(abs(Xo(s,1)-Xe(s,1))).^2;
end
e=e/M*N

Accepted Answer

Askic V
Askic V on 18 Jan 2023
This code should give you a pretty good idea how to do this:
clear
clc
u=[35 75 -35 -75 0.3 0.5];
b=u;
K=length(u)/3;% Constant1
u1=u(1:2*K);
%alpha=u(2*K+1:end);
M = 10; % Consatn2
N = 6; % Consatn3
s1=zeros(M,K);
s2=zeros(N,K);
C=zeros(M*N, length(u1)-K);
%%%%%%%%%%%%%%%%%%%
% Xo Calculation
%%%%%%%%%%%%%%%%%%%
for i=1:K
for h=1:M
s1(h,i)=exp(j*2*pi*(h-1)*0.5*sind(u1(i)));
end
for p=1:N
s2(p,i)=exp(j*2*pi*(p-1)*0.5*sind(u1(K+i)));
end
end
% Vectorization approach
i = 1:K;
s1_n=zeros(M,K);
s2_n=zeros(N,K);
h = 1:M;
s1_n(h,i)=exp(j*2*pi*(h-1).'*0.5*sind(u1(i)));
p = 1:N;
s2_n(p,i)=exp(j*2*pi*(p-1).'*0.5*sind(u1(K+i)));
% check if there is a difference
norm(s1-s1_n)
ans = 0
norm(s2-s2_n)
ans = 0
  11 Comments
Askic V
Askic V on 21 Jan 2023
Well, two for loops are correctly replaced with vectorization. However it seems that you have a lot of unnecessary (redundant) code.
You repeat calculations for s1 and s2 just to calculate Xe, signals b and u are the same, alpha and alphab have the same values. Therefore Xe and Xo have the same values.
Once gain, this is correct, change the code with for loops:
for i=1:K
for h=1:M
s1_e(h,i)=exp(j*2*pi*(h-1)*0.5*sind(bu(i)));
end
for p=1:N
s2_e(p,i)=exp(j*2*pi*(p-1)*0.5*sind(bu(K+i)));
end
end
to vectorized version:
i = 1:K;
h = 1:M;
s1(h,i)=exp(j*2*pi*(h-1).'*0.5*sind(u1(i)));
p = 1:N;
s2(p,i)=exp(j*2*pi*(p-1).'*0.5*sind(u1(K+i)));
Sadiq Akbar
Sadiq Akbar on 21 Jan 2023
Thank you very much dear Askic V for your kind response.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!