How to reduce its execution time?
Afficher commentaires plus anciens
I have the following piece of code. It works but takes time. How can we reduce its time to a very minimum value?
u=[1 3 5 7 20 30 40 50];
b=u;
Noise=5;
[R,C]=size(b);
P=C/2;
M=2*C;
%%%%%%%%%%%%%%%%%%%%
% Swapping vector b
%%%%%%%%%%%%%%%%%%%%
[~, ix] = sort(u); % u is my desired vector
[~, ix1(ix)] = sort(b);
b = b(ix1);
%%%%%%%%%%%%%%%%%%%%%%%%%%
% calculate xo
%%%%%%%%%%%%%%%%%%%%%%%%%%
xo=zeros(1,M);
for k=1:M
for i=1:P
xo(1,k)=xo(1,k)+u(i)*exp(-1i*(k-1)*pi*cosd(u(P+i)));
end
end
xo=awgn(xo,Noise);% add Noise
%%%%%%%%%%%%%%%%%%%%%
% Calculate xe
%%%%%%%%%%%%%%%%%%%%%
xe=zeros(1,M);
for k=1:M
for i=1:P
xe(1,k)=xe(1,k)+b(i)*exp(-1i*(k-1)*pi*cosd(b(P+i)));
end
end
%%%%%%%%%%%%%%%%%
% MSE
%%%%%%%%%%%%%%%%%
abc=0.0;
for m1=1:M
abc=abc+(abs(xo(1,m1)-xe(1,m1))).^2;
end
abc=abc/M;
e=abc
Réponse acceptée
Plus de réponses (1)
Hi, I vectorized your code. Using tic/toc procedure the run time is about 0.04 seconds.
Hope it helps.
tic
% transpose u and b
% we want these to be column vectors for easy vectorization
u = [1 3 5 7 20 30 40 50]';
b = u;
Noise = 5;
[R,~] = size(b);
P = R/2;
M = 2*R;
I commented the lines below, since they don't do anything. You start with u=b and you end up with u=b. Hence these steps do nothing, you will need to provide details on what you mean with "swapping b"
% % Swapping vector b
% [~, ix] = sort(u); % u is my desired vector
% [~, ix1(ix)] = sort(b);
% b = b(ix1);
% calculate xo
u1 = u( 1:P );
u2 = u( P+(1:P));
k = 1:M;
xo = sum( u1.*exp( -1i.*pi*cosd(u2).*(k-1) ) , 1);
% add Noise
xo = awgn(xo,Noise);
% Calculate xe
b1 = b( 1:P );
b2 = b( P+(1:P));
xe = sum( b1.*exp( -1i.*pi*cosd(b2).*(k-1) ) , 1);
% MSE
e = mean( abs( xo(1,:) - xe(1,:) ) .^2 )
toc
Catégories
En savoir plus sur Shifting and Sorting Matrices dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!