Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Turning a (4D matrix * 1D vector) operation into independent (3D matrix * 0D scalar) operations without loops

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

like image 249
S Chen Avatar asked Jul 12 '13 00:07

S Chen


2 Answers

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

like image 191
bla Avatar answered Nov 09 '22 17:11

bla


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
like image 1
Hugh Nolan Avatar answered Nov 09 '22 19:11

Hugh Nolan