# How can I make this code more efficient?

1 view (last 30 days)
Pooneh Shah Malekpoor on 27 Jun 2023
Commented: Stephen23 on 27 Jun 2023
Hi
This piece of code is so slow due to the big number of nx1 and nye. Could you please tell me how I can make it quicker?
Thanks
nx1=1216;
nye=160;
dx=1.973684;
dy=1.875;
nm=0;
for ip=1:nx1
for iq=1:nye
nm=nm+1;
coord(1, 1) = (ip - 1) * dx;
coord(2, 1) = (ip - 1) * dx;
coord(3, 1) = (ip - 1) * dx;
coord(5, 1) = ip * dx;
coord(6, 1) = ip * dx;
coord(7, 1) = ip * dx;
coord(4, 1) = (coord(3, 1) + coord(5, 1)) * 0.5;
coord(8, 1) = coord(4, 1);
coord(3, 2) = -(iq - 1) * dy;
coord(4, 2) = -(iq - 1) * dy;
coord(5, 2) = -(iq - 1) * dy;
coord(1, 2) = -iq * dy;
coord(8, 2) = -iq * dy;
coord(7, 2) = -iq * dy;
coord(2, 2) = (coord(1, 2) + coord(3, 2)) * 0.5;
coord(6, 2) = coord(2, 2);
for i=1:8
g_coordx(nm, i) = coord(i, 1);
g_coordy(nm, i) = coord(i, 2);
end
end
end
Stephen23 on 27 Jun 2023

KSSV on 27 Jun 2023
Read abput preallocating/ initializing the variables.
nx1=1216;
nye=160;
dx=1.973684;
dy=1.875;
nm=0;
t1 = tic ;
% See this
g_coordx = zeros(nx1*nye,8) ;
g_coordy = zeros(nx1*nye,8) ;
%
for ip=1:nx1
fprintf('% d of %d\n',ip,nx1) ;
for iq=1:nye
nm=nm+1;
coord(1, 1) = (ip - 1) * dx;
coord(2, 1) = (ip - 1) * dx;
coord(3, 1) = (ip - 1) * dx;
coord(5, 1) = ip * dx;
coord(6, 1) = ip * dx;
coord(7, 1) = ip * dx;
coord(4, 1) = (coord(3, 1) + coord(5, 1)) * 0.5;
coord(8, 1) = coord(4, 1);
coord(3, 2) = -(iq - 1) * dy;
coord(4, 2) = -(iq - 1) * dy;
coord(5, 2) = -(iq - 1) * dy;
coord(1, 2) = -iq * dy;
coord(8, 2) = -iq * dy;
coord(7, 2) = -iq * dy;
coord(2, 2) = (coord(1, 2) + coord(3, 2)) * 0.5;
coord(6, 2) = coord(2, 2);
for i=1:8
g_coordx(nm, i) = coord(i, 1);
g_coordy(nm, i) = coord(i, 2);
end
end
end
t1 = toc(t1) ;

Swastik on 27 Jun 2023
Edited: Swastik on 27 Jun 2023
• Assuming you have not preallocated the variables g_coordx & g_coordy, you can consider preallocating them to improve time and performance of the code. Read about it here
• The first part of the loops only depend on variable ip, so you can write it out of the loop
So the final code is:
nx1=1216;
nye=160;
dx=1.973684;
dy=1.875;
nm=0;
g_coordx = zeros(nx1*nye, 8);
g_coordy = zeros(nx1*nye, 8);
coord = zeros(8, 2);
for ip = 1:nx1
coord(1, 1) = (ip - 1) * dx;
coord(2, 1) = (ip - 1) * dx;
coord(3, 1) = (ip - 1) * dx;
coord(5, 1) = ip * dx;
coord(6, 1) = ip * dx;
coord(7, 1) = ip * dx;
coord(4, 1) = (coord(3, 1) + coord(5, 1)) * 0.5;
coord(8, 1) = coord(4, 1);
for iq = 1:nye
nm = (ip - 1) * nye + iq; % In case you need nm later when you modify it
coord(3, 2) = -(iq - 1) * dy;
coord(4, 2) = -(iq - 1) * dy;
coord(5, 2) = -(iq - 1) * dy;
coord(1, 2) = -iq * dy;
coord(8, 2) = -iq * dy;
coord(7, 2) = -iq * dy;
coord(2, 2) = (coord(1, 2) + coord(3, 2)) * 0.5;
coord(6, 2) = coord(2, 2);
g_coordx(nm, :) = coord(:, 1)';
g_coordy(nm, :) = coord(:, 2)';
end
end
You can also go through Techniques to improve performance