How to replace all for-loops ?
2 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Sadiq Akbar
am 10 Jan. 2023
Kommentiert: Jan
am 11 Jan. 2023
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 Kommentare
Jan
am 11 Jan. 2023
I've moved Dyuman Joshi's comment to the answers section, such that it can be accepted now.
Akzeptierte Antwort
Dyuman Joshi
am 11 Jan. 2023
Verschoben: Jan
am 11 Jan. 2023
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 Kommentare
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Startup and Shutdown finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!