# How to remove all for-loops with vectorization?

7 views (last 30 days)
Sadiq Akbar on 18 Jan 2023
Commented: Sadiq Akbar on 21 Jan 2023
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

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
Sadiq Akbar on 21 Jan 2023

### Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

### Community Treasure Hunt

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

Start Hunting!

Translated by