How to vectorize this piece of code by replacing all the for-loops?
Show older comments
I want to vectorize the following piece of code so that it becomes fast. But M and N can be only coprime numbers and N < M always. I tried but failed badly.
th=pi/180;
u=[40*th 50*th 60*th 70*th];
b=u;
K=length(u);
% Note that N<M coprime No
N=3; M=4;
NE=(N+M-1); % Total
x=0; y=0; z=1; % Initialization
Sto=zeros(NE,K); % matrix initialization
for ii=1:NE
if (x==0);
distance=0;
x=x+1;
elseif (y==0);
distance=z*pi*N;
y=y+1;
else
distance=z*pi*M;
y=0;
z=z+1;
end
for jj=1:K
Sto(ii,jj)=exp(-1i*distance*cos(u(jj))); % matrix equation
end
end
y_act_sum=sum(Sto,2);
y_act_abs=abs(y_act_sum);
xx=(y_act_abs);
x=0;y=0;z=1;
Ste=zeros(NE,K);
for kk=1:NE
if (x==0);
distance=0;
x=x+1;
elseif (y==0);
distance=z*pi*N;
y=y+1;
else
distance=z*pi*M;
y=0;
z=z+1;
end
for i=1:K
Ste(kk,i)=exp(-1i*distance*cos(b(i)));
end
end
%%%%%%%%%%%%%%%%%%%%%%%%
% MSE
%%%%%%%%%%%%%%%%%%%%%%%%
y_est_sum=sum(Ste,2);
y_est_abs=abs(y_est_sum);
yy=(y_est_abs);
correlation=corr(xx,yy);
mse1=zeros(1,NE);
for pp=1:NE
mse1=(xx(pp)-yy(pp));
end
mse2=sum(mse1,2);
mse3=mse2.^2;
mse=mse3/NE;
mse_corr=mse+norm(correlation-1);
Accepted Answer
More Answers (1)
Sulaymon Eshkabilov
on 3 Jan 2023
Here is the vectorized code without any loops:
th=pi/180;
u=[40*th 50*th 60*th 70*th];
b=u;
K=length(u);
% Note that N<M coprime No
N=3; M=4;
NE=(N+M-1); % Total
distance = [0*pi*N; 1*pi*N; 1*pi*M; 2*pi*N; 2*pi*M; 3*pi*N];
STO_1 = exp(-1i*distance(:)*cos(u));
y_act_sum=sum(Sto,2);
y_act_abs=abs(y_act_sum);
xx=(y_act_abs);
STE_1 = exp(-1i*distance(:)*cos(b));
%%%%%%%%%%%%%%%%%%%%%%%%
% MSE
%%%%%%%%%%%%%%%%%%%%%%%%%
y_est_sum=sum(Ste,2);
y_est_abs=abs(y_est_sum);
yy=(y_est_abs);
correlation=corr(xx,yy);
mse1=(xx-yy);
mse2=sum(mse1,2);
mse3=mse2.^2;
mse=mse3/NE;
mse_corr=mse+norm(correlation-1);
Categories
Find more on Debugging and Improving Code 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!