Generating arrays using bsxfun with anonymous function and for elementwise subtractions - MATLAB

后端 未结 1 856
一向
一向 2020-12-12 00:31

I have the following code:

n = 10000; 
s = 100;
Z = rand(n, 2);
x = rand(s, 1);
y = rand(s, 1);
fun = @(a) exp(a);

In principle, the anonym

相关标签:
1条回答
  • 2020-12-12 00:59

    Code

    exp_Z_x = exp(bsxfun(@minus,Z(:,1),x.')); %//'
    exp_Z_y = exp(bsxfun(@minus,Z(:,2),y.')); %//'
    out1 = bsxfun(@times,exp_Z_x,permute(exp_Z_y,[1 3 2]));
    
    Z1 = [ones(n,1) Z(:,1) Z(:,2)];
    X1 = permute([ zeros(s,1) x zeros(s,1)],[3 2 1]);
    Y1 = permute([ zeros(s,1) zeros(s,1) y],[4 2 3 1]);
    out2 = bsxfun(@minus,bsxfun(@minus,Z1,X1),Y1);
    
    out3 = zeros(n,n,s,s); %// out3(n,n,s,s) = 0; could be used for performance
    out3(bsxfun(@plus,[1:n+1:n*n]',[0:s*s-1]*n*n)) = out1; %//'
    
    %// out1, out2 and out3 are the desired outputs
    
    0 讨论(0)
提交回复
热议问题