开发者

Speed up `for` loops or vectorizing them

开发者 https://www.devze.com 2023-02-25 21:48 出处:网络
I have write some code but my program is too slo开发者_JAVA技巧w. The problem is as follows: I\'ll build Matrix \"A\" to solve Ax=b problem

I have write some code but my program is too slo开发者_JAVA技巧w. The problem is as follows:

I'll build Matrix "A" to solve Ax=b problem

I have a sphere(it may be any shape), that is showed by some point,

I have assigned a coordinate vector [x y z] for each point.

N is the number of points.

Please first load (a)

clc 
[rv,N,d0]=geometrySphere(5e-9,10);         %#  Nx3 matrix [x1 y1 z1;x2 y2 z2;... ].

%# geometrySphere is a function for replacicg the sphere with points.
 L=(301:500)*1e-9;  K=2*pi./L;                   %# 1x200 array 
 %some constants ==================
 I=eye(3);
 e0=1;
 V=N*d0^3; aeq=(3*V/(4*pi))^(1/3);
 E0y=ones(N,1);
 E0z=E0y;
 Cext=zeros(1,200);
 Qext=zeros(1,200);
 A=zeros(3,3,N^2);
 %=================================
for i=1:N
    r(i)=sqrt(rv(i,1)^2+rv(i,2)^2+rv(i,3)^2);    %# r is the size of each vector 
end
for i=1:N
    for j=1:N
        dx(i,j)=rv(i,1)-rv(j,1); %# The x component of distance between each 2 point
        dy(i,j)=rv(i,2)-rv(j,2);
        dz(i,j)=rv(i,3)-rv(j,3);
    end
end
d=cat(3,dx,dy,dz);  %# d is the distance between each 2 point (a 3D matrix)
nd=sqrt(dx.^2+dy.^2+dz.^2);                     %# Norm of rv vector
nx=d(:,:,1)./nd; ny=d(:,:,2)./nd; nz=d(:,:,3)./nd;
n=cat(3,nx,ny,nz);                              %# Unit vectors for points that construct my sphere


 for s=1:length(L)
    E0x=exp(1i*K(s)*rv(:,1))';                   
    % 1x200 array  in direction of x(in Cartesian coordinate system)
    % Main Loop    =================================================
    p=1;                                                        
    for ii=1:N                                                  
        for jj=1:N                                              
            if ii==jj                                           
                A(:,:,p)=a(s)*eye(3);           %# 3x3 , a is a 1x200 constant array                        
                p=p+1;                          %# p is only a counter              
            else                                                
            A(:,:,p)=-exp(1i*K(s)*nd(ii,jj))/nd(ii,jj)*(-K(s)^2*([nx(ii,jj);ny(ii,jj);nz(ii,jj)]... 
                *[nx(ii,jj) ny(ii,jj) nz(ii,jj)]-I)+(1/nd(ii,jj)^2-1i*K(s)/nd(ii,jj))...             
                *(3*[nx(ii,jj);ny(ii,jj);nz(ii,jj)]*[nx(ii,jj) ny(ii,jj) nz(ii,jj)]-I));             
            p=p+1;          
            end                                             
        end                                                 
    end                                                     

%===============================================================
B = reshape(permute(reshape(A,3,3*N,[]),[2 1 3]),3*N,[]).';
%# concatenation of N^2 3x3 matrixes into a 3Nx3N matrix
    for i=1:N
        E00(:,i)=[E0x(i) E0y(i) E0z(i)]';
    end
    b=reshape(E00,3*N,1);
    P=inv(B)*b;
    Cext(s)=(4*pi*K(s))*imag(b'*P);
    Qext(s)=Cext(s)/(pi*aeq^2);
 end

Qmax=max(Qext); Qext=Qext/Qmax;
L=L*1e9;
plot(L,Qext,'--');figure(gcf)

I don't know could I explane clear?

Do you have any suggestion? Thanks in advance for any suggestions.

geometrySphere

Speed up `for` loops or vectorizing them

Where I is the 3x3 identity matrix and nij nij denotes a dyadic product.

Speed up `for` loops or vectorizing them

(a) after running a function is:an 1x200 array


The first two loops can be easily replaced by the following vector operations (I haven't tested it):

r=sqrt(sum(rv,2).^2);
[npoints,ndims]=size(rv);
pairs=combnk(1:npoints,2);
npairs=size(pairs,1);

index=repmat(pairs(:),ndims,1)+npoints*reshape(repmat(0:ndims-1,npairs*2,1),npairs*2*ndims,1);
d=reshape(reshape(rv(index),npairs*ndims,2)*[1 -1]',npairs,ndims);           %'
n=bsxfun(@rdivide,d,sqrt(sum(d.^2,2))); 

Note that in your case, dx, dy and dz will be skew-symmetric matrices with zero diagonals and hence only N(N-1)/2 independent elements. This pairing can be achieved by combnk, which gives all possible pairs from n items. Hence, the d here is an N(N-1)/2x3 element array, whereas your d is an NxNx3 array, yet contains the same information.

Now the main loop also looks like it can be vectorized, however its too long and I don't want to spend time going through all the indices. But here are some suggestions:

  1. You can do element-wise operations in MATLAB using a . prefix before the operator. So if you have two equi-dimensional arrays/vectors, like A=[a b c] and B=[d e f] (assume real), the dot product of the two vectors is simply A.*B, which gives [ad be cf]. Similar rules for division and raising it to a power. You can read more about it here.
  2. You can do matrix multiplications using the * operator (no dot here), and the inner dimensions must match. So with the above example, the inner product is simply A*B', which gives you ad+be+cf, and the outer product (dyadic product) is A'*B, which gives you a 3x3 matrix:[ad ae af;bd be bf;cd ce cf]
0

精彩评论

暂无评论...
验证码 换一张
取 消