Geoffrey Xiao
Geoffrey Xiao

Reputation: 77

Linear combination of the Slices in a 3D

I have a 3D matrix sized (x,y,N) and a 2D matrix sized (N,N).

I would like to manipulate the two in a way that each column in the 2D matrix has the coefficients for a linear combination of the 2D sized- (x, y) slices in the 3D matrix. And I would like to do this for all N columns in the 2D matrix.

Schematically,

Schematic Picture Link

Currently the code looks like:

A = zeros(numel(x_axis), numel(y_axis), N);
B = zeros(numel(x_axis), numel(y_axis), N);
C = zeros(N, N)
for i = 1 : N
    for j = 1 : N
        A(:,:,i) = A(:,:,i) + B(:,:,j) * C(j,i);
    end
end

But it is quite slow. Is there any way to speed up the MATLAB code by vectorizing?

Upvotes: 3

Views: 167

Answers (2)

Florian
Florian

Reputation: 1824

If I understand your problem well, then this should work:

[p,q,N] = size(B);
A = reshape( reshape(B, [p*q, N]) * C, [p, q, N]);

edit: Cleaner version suggested by Suever:

A = reshape(reshape(B, [], size(B, 3)) * C, size(B))

Generalization to the R-D case:

A = reshape(reshape(B, [], size(B, ndims(B))) * C, size(B))

Upvotes: 2

Suever
Suever

Reputation: 65460

You can use bsxfun which will calculate this very quickly for you. We have to use permute to re-arrange C a little bit to ensure that it has conformant dimensions for using bsxfun and then we perform the summation along the third dimension of the resulting output and apply squeeze to remove the singleton third dimension.

A = squeeze(sum(bsxfun(@times, B, permute(C, [3 4 1 2])), 3))

Upvotes: 2

Related Questions