How to replace all for-loops ?
2 次查看(过去 30 天)
显示 更早的评论
I had posted a function here for vectorization. Now this is the same function and even I tried myself to replace all for-loops like previous but I didn't succeed because in this the outer loop has enclosed all the for-loops and instead of pop being a vector, now it is a matrix due to which I failed to do so. The code is:
clear all; clc
u=[1 2 10 20];
dim=length(u);
pop=rand(10,dim);
C = size(pop,2);
P=C/2;
M=2*C;
e = zeros(size(pop,1),1);
for ii = 1:size(pop,1)
% calculate xo
b = pop(ii,:);
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*cos(u(P+i)));
end
end
% 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*cos(b(P+i)));
end
end
abc=0.0;
for m1=1:M
abc=abc+(abs(xo(1,m1)-xe(1,m1))).^2;
end
abc=abc/M;
e(ii)=abc
end
18 个评论
Jan
2023-1-11
I've moved Dyuman Joshi's comment to the answers section, such that it can be accepted now.
采纳的回答
Dyuman Joshi
2023-1-11
移动:Jan
2023-1-11
That would be something like this -
e1=vector;
e2=twofor;
%comparing results from both methods
result_comparison=isequal(e1,e2)
fprintf('time taken by vector method = %e seconds', timeit(@vector))
fprintf('time taken by double for loop method = %e seconds', timeit(@twofor))
function e = vector
rng(1)
u = [1 2 10 20];
pop = rand(10, numel(u));
P = width(pop)/2;
M = width(pop)*2;
H = height(pop);
e=zeros(H,1);
xo=zeros(1,M);
xe=zeros(1,M);
for ii = 1:H
b=pop(ii,:);
xo=(exp(-1i*(0:M-1)'*pi*cos(u(P+1:2*P)))*u(1:P)')';
xe=(exp(-1i*(0:M-1)'*pi*cos(b(P+1:2*P)))*b(1:P)')';
e(ii)=sum(abs(xo-xe).^2)/M;
end
end
function e = twofor
rng(1)
u = [1 2 10 20];
pop = rand(10, numel(u));
P = width(pop)/2;
M = width(pop)*2;
H = height(pop);
e = zeros(H,1);
for ii = 1:H
b = pop(ii,:);
xo = zeros(1,M);
xe = zeros(1,M);
abc = 0;
for jj=1:M
for kk=1:P
xo(1,jj) = xo(1,jj) + u(kk) * exp(-1i*(jj-1) * pi * cos(u(P+kk)));
xe(1,jj) = xe(1,jj) + b(kk) * exp(-1i*(jj-1) * pi * cos(b(P+kk)));
end
abc = abc+(abs(xo(1,jj)-xe(1,jj))).^2;
end
e(ii) = abc/M;
end
end
0 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Startup and Shutdown 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!