Is it possible to vectorize for loop or otherwise make this code more efficient?
Show older comments
Can someone please help with code efficiency? The code is as follows:
Qx=zeros(Q_xlkm,Q_ylkm); % Q_xlkm = 201, Q_ylkm = 21
Qy=zeros(Q_xlkm,Q_ylkm);
for i=1:Q_ylkm
Qx(:,i)=xxQ; % xxQ= 1x201 vector containing x-coordinates
end
for i=1:Q_xlkm
Qy(i,:)=yyQ; % yyQ= 1x21 vector containing y-coordinates
end
for x=1:101
for y=1:21
for z=1:100
x1=xx(x); % xx= 1x101 vector containing x-coordinates
y1=yy(y); % yy= 1x21 vector containing y-coordinates
z1=zz(z); % zz= 1x100 vector containing z-coordinates
X=Qx-x1; % 201x21 matrix containing the difference in x for each load and current x-coordinate
Y=Qy-y1; % 201x21 matrix containing the difference in y for each load and current y-coordinate
X2=X.^2; % Elementwise square of x-differences
Y2=Y.^2; % Elementwise square of y-differences
r_apu=X2+Y2;
Z=Qz-z1; % 201x21 matrix containing the difference in z for each load and current z-coordinate
Z(Z<1)=1;
Z2=Z.^2;
Z3=Z.^3;
QqZ3=Qq.*Z3;
r2Z2=r_apu+Z2;
r2Z2_potenssi=r2Z2.^(-5/2);
sig=QqZ3.*r2Z2_potenssi;
dsig=(3/(2*pi))*sig; % 201x21 Matrix. An element of this matrix is the stress in a point P(x,y,z) due to load Q(x,y,z,q)
P(x,y,z)=sum(sum(dsig)); % Stress in a point P(x,y,z) due to all loads
end
end
end
The main equation for this code is as follows:

For clarification, the p coordinates are as follows: xx=0:1:100 yy=0:1:20 zz=-10:0.1:-0.1
Q coordinates: xxQ = 0:0.5:100 yyQ = 0:1:20 z-coordinate depends on x,y and is in the range of 0:1
Basically what I want to do is for each x,y,z point in 101x21x100 3D-matrix P, I want to calculate loads from each load with coordinates x,y,z and quantity (defined by 201x21 matrices Qx,Qy,Qz and Qq) and then sum all the loads into each x,y,z point in P. Is there a way to do this more efficiently? Thanks!
2 Comments
John Chilleri
on 26 Dec 2016
You can simplify the first two loops pretty easily,
for i=1:Q_ylkm
Qx(:,i)=xxQ; % xxQ= 1x201 vector containing x-coordinates
end
for i=1:Q_xlkm
Qy(i,:)=yyQ; % yyQ= 1x21 vector containing y-coordinates
end
% Change the above to:
Qx(:,1:Q_ylkm) = xxQ;
Qy(1:Q_xlkm,:) = yyQ;
Answers (1)
Image Analyst
on 26 Dec 2016
In addition to what John said above, you could do this:
for x=1:101
x1=xx(x); % xx= 1x101 vector containing x-coordinates
for y=1:21
y1=yy(y); % yy= 1x21 vector containing y-coordinates
for z=1:100
z1=zz(z); % zz= 1x100 vector containing z-coordinates
You could also call sum() just once:
P(x, y, z) = sum(dsig(:));
Beyond that, I don't know, because I don't really know what this code is doing due to the lack of comments. Please consider adding comments.
Categories
Find more on Half-Normal Distribution in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!