How to reduce the execution time of the given piece of code?

I have an algorithm "WHO", a function "fobjNoise" and a script "main". I run the main and I get different values of fitness for Noise that is varying from 0 to 40 dB. Then I plot the fitness vs Noise graph. But there are two issues. These are:
1- This code takes too much time. I want to reduce it execution time.
2-When I do pre-allocation for the variables onev, twov etc, like below:
Runs = 50; % Number Of Times To Run The Inner Loop
onev=zeros(Runs,1);
time1=zeros(Runs,1);
two1=zeros(Runs,dim);
twov=zeros(Runs,dim);
then when I try to plot the fitness values obtained , it gives me an error like below:
>> onev=sort(onev,'descend');
>> plot(Noise,onev)
Error using plot
Vectors must be the same length.
>>
Why it is so and what to do so that it takes less time and doesn't give me the error even if I increase the no. of Runs or I vary the Noise levels from 0 to 50 or from -40 to 40 etc.?

9 comentarios

Without the code it is (almost) impossible for us to suggest anything.
"..., it gives me an error like below. Why it is so"
The error is pretty clear about why that happens.
Errors in MATLAB are a great feature, not only do they state where the error occurs, they also state why the error occurs and sometimes provide info on how to solve them. You should read them.
There's no real way to know if or how you can make a bit of code faster without knowing what the code is. The changes that could be made might be anything from very small subtle things to large changes to a workflow. I can understand if you're reluctant to reveal certain things, but without details, the advice that can be given is very limited.
As to why the vectors change in length, my guess is that there's something going on that's causing values to be assigned to rows/columns beyond Runs,dim respectively. Something like
x = zeros(1,10) % only 10 elements
x = 1×10
0 0 0 0 0 0 0 0 0 0
x(12) = 3 % assignment beyond the end of the array causes expansion if the expansion is unambiguous
x = 1×12
0 0 0 0 0 0 0 0 0 0 0 3
If that's happening a lot within the loop, the expansion might be one thing that contributes to an increased execution time. As mentioned, it's unclear if there are others.
Sadiq Akbar
Sadiq Akbar el 5 de En. de 2024
Editada: Torsten el 5 de En. de 2024
Thanks a lot dear Dyuman Joshi for your prompt response. Actually I attached the cdes but the post was not successful that's why I posted it by retrying. So the codes are not uploaded. All the three codes are attached here.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Varying Noise from 0dB to 40dB code
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
clear;clc
u=[1 1.5 -36 36]; % desired vector
dim=length(u);
lb=[0*ones(1,dim/2) -90*ones(1,dim/2)];
ub=[5*ones(1,dim/2) 90*ones(1,dim/2)];
Noise=0:40;% Varying Noise
[~,C]=size(u);
P=C/2;
M=C/2;
k = (-(M/2-1):M/2).';
i = (1:P);
Runs = 100; % Number Of Times To Run The Inner Loop
for mm=1:numel(Noise)
for nn = 1:Runs
%[time,gBest,gBestScore]=WHO(30,500,lb,ub,dim,objectiveFunctionForMetaheuristic);
[time,gBest,gBestScore]=WHO(30,500,lb,ub,dim,@(x) fobjNoise(x,u,P,M,k,i,Noise(mm)));
onev(nn) = gBestScore;%fmin;%fval;%onev(nn,:) = fval;
twov(nn,:) = gBest;%best;%B;
time1(nn)=time;
%%%%%%%%%%%%%%%%%%%%%
% Swapping
%%%%%%%%%%%%%%%%%%%%%
[~, ix] = sort(u); % u is my desired vector
[~, ix1(ix)] = sort(twov(nn,:)); %[~, ix1(ix)] = sort(temp(nn,:));
two1(nn,:) = twov(nn,ix1);%two(nn,:) = temp(nn,ix1);
end
[~,idx] = min(onev); % Choose Lowest 'gBestScore' For Each Run
one(mm,:)=onev(idx); % Save That 'gBestScore' Value
%two(mm,:)=twov(idx,:);
two(mm,:)=two1(idx,:);
end
onev=sort(onev,'descend');
%%%%%%%%%%%%%%%%%%%%
% Save workspace data
%%%%%%%%%%%%%%%%%%%%
%save 2snAll
function penalty = penaltyTerm(x, desiredResult)
% Define a penalty term based on the deviation from the desired result
penalty = 100 * sum((x - desiredResult).^2);
end
function e=fobjNoise(b,u,P,M,k,i,Noise)
% [R,C]=size(b);
% P=C/2;
% M=2*C;
% k = (-(M/2-1):M/2).';
% i = (1:P);
xo = sum(1*exp(1i*((k).*(-pi/2).*sin(u(P+i))+((k).^2.*pi./(16*u(i))).*cos(u(P+i)).^2)),2);
xo=awgn(xo,Noise);% Add Noise
xe = sum(1*exp(1i*((k).*(-pi/2).*sin(b(P+i))+((k).^2.*pi./(16*b(i))).*cos(b(P+i)).^2)),2);
%%%%%%%%%%%%%%%%%%
% MSE
%%%%%%%%%%%%%%%%%%
e=norm(xo-xe).^2/(M);
end
% Source codes demo version 1.0
% _____________________________________________________
% Author, inventor and programmer: Iraj Naruei and Farshid Keynia,
% e-Mail: irajnaruei@iauk.ac.ir , irajnaruei@yahoo.com
% _____________________________________________________
% Co-author and Advisor: Farshid Keynia
%
% e-Mail: fkeynia@gmail.com
% _____________________________________________________
% Co-authors: Amir Sabbagh Molahoseyni
%
% e-Mail: sabbagh@iauk.ac.ir
% _____________________________________________________
% You can find the Wild Horse Optimizer code at
% _____________________________________________________
%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Max_iter: maximum iterations, N: populatoin size, Convergence_curve: Convergence curve
%function [Convergence_curve,gBest,gBestScore]=WHO(N,Max_iter,lb,ub,dim,fobj)
function [time,gBest,gBestScore]=WHO(N,Max_iter,lb,ub,dim,fobj)
tic; % By Me
if size(ub,1)==1
ub=ones(1,dim).*ub;
lb=ones(1,dim).*lb;
end
PS=0.2; % Stallions Percentage
PC=0.13; % Crossover Percentage
NStallion=ceil(PS*N); % number Stallion
Nfoal=N-NStallion;
Convergence_curve = zeros(1,Max_iter);
gBest=zeros(1,dim);
gBestScore=inf;
%create initial population
empty.pos=[];
empty.cost=[];
group=repmat(empty,Nfoal,1);
for i=1:Nfoal
group(i).pos=lb+rand(1,dim).*(ub-lb);
group(i).cost=fobj(group(i).pos);
end
Stallion=repmat(empty,NStallion,1);
for i=1:NStallion
Stallion(i).pos=lb+rand(1,dim).*(ub-lb);
Stallion(i).cost=fobj(Stallion(i).pos);
end
ngroup=length(group);
a=randperm(ngroup);
group=group(a);
i=0;
k=1;
for j=1:ngroup
i=i+1;
Stallion(i).group(k)=group(j);
if i==NStallion
i=0;
k=k+1;
end
end
Stallion=exchange(Stallion);
[value,index]=min([Stallion.cost]);
WH=Stallion(index); % global
gBest=WH.pos;
gBestScore=WH.cost;
Convergence_curve(1)=WH.cost;
l=2; % Loop counter
while l<Max_iter+1
TDR=1-l*((1)/Max_iter);
for i=1:NStallion
ngroup=length(Stallion(i).group);
[~,index]=sort([Stallion(i).group.cost]);
Stallion(i).group=Stallion(i).group(index);
for j=1:ngroup
if rand>PC
z=rand(1,dim)<TDR;
r1=rand;
r2=rand(1,dim);
idx=(z==0);
r3=r1.*idx+r2.*~idx;
rr=-2+4*r3;
Stallion(i).group(j).pos= 2*r3.*cos(2*pi*rr).*(Stallion(i).pos-Stallion(i).group(j).pos)+(Stallion(i).pos);
else
A=randperm(NStallion);
A(A==i)=[];
a=A(1);
c=A(2);
% B=randperm(ngroup);
% BB=randperm(ngroup);
% b1=B(1);b2=BB(1);
x1=Stallion(c).group(end).pos;
x2=Stallion(a).group(end).pos;
y1=(x1+x2)/2; % Crossover
Stallion(i).group(j).pos=y1;
end
Stallion(i).group(j).pos=min(Stallion(i).group(j).pos,ub);
Stallion(i).group(j).pos=max(Stallion(i).group(j).pos,lb);
Stallion(i).group(j).cost=fobj(Stallion(i).group(j).pos);
end
% end
%
% for i=1:NStallion
R=rand;
% z=rand(1,dim)<TDR;
% r1=rand;
% r2=rand(1,dim);
% idx=(z==0);
% r3=r1.*idx+r2.*~idx;
% rr=-2+4*r3;
if R<0.5
k= 2*r3.*cos(2*pi*rr).*(WH.pos-(Stallion(i).pos))+WH.pos;
else
k= 2*r3.*cos(2*pi*rr).*(WH.pos-(Stallion(i).pos))-WH.pos;
end
k=min(k,ub);
k=max(k,lb);
fk=fobj(k);
if fk<Stallion(i).cost
Stallion(i).pos =k;
Stallion(i).cost=fk;
end
end
Stallion=exchange(Stallion);
[value,index]=min([Stallion.cost]);
if value<WH.cost
WH=Stallion(index);
end
gBest=WH.pos;
gBestScore=WH.cost;
Convergence_curve(l)=WH.cost;
l = l + 1;
time=toc; % By Me
end
end
function Stallion=exchange(Stallion)
nStallion=length(Stallion);
for i=1:nStallion
[value,index]=min([Stallion(i).group.cost]);
if value<Stallion(i).cost
bestgroup=Stallion(i).group(index);
Stallion(i).group(index).pos=Stallion(i).pos;
Stallion(i).group(index).cost=Stallion(i).cost;
Stallion(i).pos=bestgroup.pos;
Stallion(i).cost=bestgroup.cost;
end
end
end
function [X]=initialization(N,dim,up,down)
if size(up,1)==1
X=rand(N,dim).*(up-down)+down;
end
if size(up,1)>1
for i=1:dim
high=up(i);low=down(i);
X(:,i)=rand(1,N).*(high-low)+low;
end
end
end
Aquatris
Aquatris el 5 de En. de 2024
Editada: Aquatris el 5 de En. de 2024
You have a lot of for loops. I think you can vectorize some of them on a first look to reduce execution time. Vectorization topic Link here
@Sadiq Akbar: You should
plot(Noise,one)
instead of
plot(Noise,onev)
because onev has Runs elements whereas one has numel(Noise) elements.
Thanks a lot @DGM, @Aquatris, @Voss and @Torsten for your kind responses.
@Torsten : You have just reproduced my code. You have not done any changes. So I don't understand what do you mean?
@DGM : I have already given the full code, and I have not hidden anything. But still if you want some information, you can ask me.
@Voss : This will not reduce my execution time.
"This will not reduce my execution time."
That's true. That's why I put it as a comment and not an answer. My intent was to explain the error you encountered and to propose an error-free alternative.
By the way, I imagine Torsten edited your comment to fix the code formatting.
Torsten
Torsten el 6 de En. de 2024
Editada: Torsten el 6 de En. de 2024
You have just reproduced my code. You have not done any changes. So I don't understand what do you mean?
I don't want to enter the discussion. I just added initialization.m and exchange.m from the file exchange that you forgot to include.
My problem is still not resolved. However, I am happy that at least you all have tried, that's why I am thankful to all of you.

Iniciar sesión para comentar.

Respuestas (1)

Taylor
Taylor el 8 de En. de 2024
The Profiler is the perfect tool for this. You will be able to see a thorough breakdown of the runtime of your code, and identify which functions are taking the most time. There are also some common ways to speed up code outlined here

Preguntada:

el 5 de En. de 2024

Respondida:

el 8 de En. de 2024

Community Treasure Hunt

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

Start Hunting!

Translated by