20.08.2015 Views

MATLAB array manipulation tips and tricks

MATLAB array manipulation tips and tricks - Home - Online.no

MATLAB array manipulation tips and tricks - Home - Online.no

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 10Basic arithmetic operations10.1 Multiply <strong>array</strong>s10.1.1 Multiply each 2D slice with the same matrix (element-by-element)Assume X is an m-by-n-by-p-by-q-by-. . . <strong>array</strong> <strong>and</strong> Y is an m-by-n matrix <strong>and</strong> you want to constructa new m-by-n-by-p-by-q-by-. . . <strong>array</strong> Z, whereZ(:,:,i,j,...) = X(:,:,i,j,...) .* Y;for all i=1,...,p, j=1,...,q, etc. This can be done with nested for-loops, or by the followingvectorized codesx = size(X);Z = X .* repmat(Y, [1 1 sx(3:end)]);10.1.2 Multiply each 2D slice with the same matrix (left)Assume X is an m-by-n-by-p-by-q-by-. . . <strong>array</strong> <strong>and</strong> Y is a k-by-m matrix <strong>and</strong> you want to constructa new k-by-n-by-p-by-q-by-. . . <strong>array</strong> Z, whereZ(:,:,i,j,...) = Y * X(:,:,i,j,...);for all i=1,...,p, j=1,...,q, etc. This can be done with nested for-loops, or by the followingvectorized codesx = size(X);sy = size(Y);Z = reshape(Y * X(:,:), [sy(1) sx(2:end)]);The above works by reshaping X so that all 2D slices X(:,:,i,j,...) are placed next to eachother (horizontal concatenation), then multiply with Y, <strong>and</strong> then reshaping back again.The X(:,:) is simply a short-h<strong>and</strong> for reshape(X, [sx(1) prod(sx)/sx(1)]).10.1.3 Multiply each 2D slice with the same matrix (right)Assume X is an m-by-n-by-p-by-q-by-. . . <strong>array</strong> <strong>and</strong> Y is an n-by-k matrix <strong>and</strong> you want to constructa new m-by-n-by-p-by-q-by-. . . <strong>array</strong> Z, where30

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!