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
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With