Search code examples
matlabmatrixmatrix-multiplication

Multiplying a 4D matrix by a vector, and collapsing 1 dimension


I have a question regarding the multiplication of a 4-dimensional object by a 1 dimensional object. Effectively, I have a 4D object of sizes (15,15,3,5). I want to multiply out the 4th dimension by using a 5x1 vector, collapsing the last dimension to 1. Then I want to use squeeze to get a (15,15,3) sized object, again multiplying it by a 3x1 vector, leaving me with a 15x15 matrix.

I can do this in a loop, but that is quite costly. Can anyone give me suggestions how to do this without a loop?

For now the loop:

expectationCalc = reshape(mValueFunction(age+1, :, :, :, :), nGridAssets, nGridHumanCapital, nNetInterestRate, nShockstoHumanCapital);
for i = 1:nGridAssets
    for j = 1:nGridHumanCapital
        expectation(i,j) = mTransitionNetInterestRate(nNetIntRate, :)*(squeeze(expectationCalc(i,j,:,:))*mTransitionShockHumanCapital(ShockHcapital, :)');
    end
end 

Solution

  • If you reshape your 4D matrix to a 2D matrix, where the 2nd dimension is the one you want to reduce by dot product, and the 1st dimension contains all other dimensions, then you can apply a regular matrix multiplication. The result can then be reshaped to the original size (minus one dimension):

    % Input data
    M = randn(15,15,3,5);
    v1 = randn(5,1);
    v2 = randn(3,1);
    
    % 1st multiplication
    sz = size(M);
    M = reshape(M,[],sz(end));
    M = M * v1;
    sz(end) = [];       % We no longer have that last dimension
    M = reshape(M,sz);
    
    % 2nd multiplication
    M = reshape(M,[],sz(end));
    M = M * v2;
    sz(end) = [];       % We no longer have that last dimension
    M = reshape(M,sz);