フィルターのクリア

How to replace all for-loops ?

6 ビュー (過去 30 日間)
Sadiq Akbar
Sadiq Akbar 2023 年 1 月 10 日
コメント済み: Jan 2023 年 1 月 11 日
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 件のコメント
Sadiq Akbar
Sadiq Akbar 2023 年 1 月 11 日
Thanks a lot dear Dyuman Joshi for your kind response. Yes, i want to accept your answer and give vote to others also but how because vote icon is not visible with others?
Jan
Jan 2023 年 1 月 11 日
I've moved Dyuman Joshi's comment to the answers section, such that it can be accepted now.

サインインしてコメントする。

採用された回答

Dyuman Joshi
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)
result_comparison = logical
1
fprintf('time taken by vector method = %e seconds', timeit(@vector))
time taken by vector method = 3.112200e-04 seconds
fprintf('time taken by double for loop method = %e seconds', timeit(@twofor))
time taken by double for loop method = 2.392200e-04 seconds
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 件)

カテゴリ

Help Center および File ExchangeStartup and Shutdown についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by