5
votes

Is there any way to vectorize the following:

    for i = 1:6
        te = k(:,:,:,i).*(c(i));
    end

I'm trying to multiply a 4D matrix, k, by a vector, c, by breaking it up into independent (3D matrix * scalar) operations. I already have two other unavoidable for loops within a while loop in this function file, and am trying my best to avoid loops.

Any insight on this will be much appreciated!

-SC

2
A for loop is probably your best option for anything more than 2D matrix.Bee
I was afraid that might be the case. Tried playing around with matrix indexing; e.g. k([3, 3; 3 3]) to see what'd happen, but got super confused. Unsure if it's the right alley to go down anyway.S Chen

2 Answers

5
votes

You can do this using MTIMESX - a Fast matrix multiplication tool with multidimensional support by James Tursa, found in Matlab's file exchange.

It is as simple as:

C = mtimesx(A,B) 

performs the calculation C = A * B

1
votes

Unless I'm missing something, this is a case for bsxfun:

te=bsxfun(@times, k, permute(c,[3 4 1 2])); % c is a row vector

Or

te=bsxfun(@times, k, permute(c,[3 4 2 1])); % c is a column vector

This is assuming that the 4th dimension of k has the same size as c. If not, then you can use submatrix indexing:

te=bsxfun(@times, k(:,:,:,1:length(c)), permute(c,[3 4 2 1])); % c is a column vector