Search code examples
arraysmatlabperformancecomputation

Output arrayfun into trid dimension of the matrix in MATLAB


Assume that I have a matrix A = rand(n,m). I want to compute matrix B with size n x n x m, where B(:,:,i) = A(:,i)*A(:,i)'; The code that can produce this is quite simple:

A = rand(n,m); B = zeros(n,n,m);
for i=1:m
B(:,:,i) = A(:,i)*A(:,i)'
end

However, I am concerned about speed and would like to ask you help to tell me how to implement it without using loops. Very likely that I need to use either bsxfun, arrayfun or rowfun, but I am not sure. All answers are appreciated.


Solution

  • I don't have MATLAB at hand right now, but I think this code should produce the same result as your loop:

    A1 = reshape(A,n,1,m);
    A2 = reshape(A,1,n,m);
    B = bsxfun(@times,A1,A2);
    

    If you have a newer version of MATLAB, you don't need bsxfun any more, you can just write

    B = A1 .* A2;
    

    On older versions this last line will give an error message.

    Whether any of this is faster than your loop depends also on the version of MATLAB. Newer MATLAB versions are not slow any more with loops. I think the loop is more readable, it's worth using more readable code, or at least keep the loop in a comment to clarify what the vectorized code does.