Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

3d matrix by column vector multiplication

I have a 3d (or in general n-dimensional) matrix A with dimensions

size(A) = [d1 d2 d3 ... dn]. 

Now I want to do a vector multiplication with a column vector v over one of the dimensions (as I would do in 2 dimensions, where I get a vector returned - for instance for d1 = 2, d3 = 4 and size(v) = d2), so that

(A*d)_i = sum(a_ij*v_j). 

Hence I want to reduce by one dimension.

Is there a Matlab function(other than looping) that returns for a d3-dimensional column vector v

(A*v)_ij = sum(A_ijk*v_k). 

I hope this was clear.

Thanks!

like image 590
user1763302 Avatar asked Oct 21 '12 16:10

user1763302


Video Answer


2 Answers

You can do that with a few reshape's:

A=rand(2,3,4);
v=rand(1,4);
reshape(reshape(A,[size(A,1)*size(A,2),size(A,3)])*v,[size(A,1) size(A,2)])

Basically, you reshape A into a 2D matrix A2((ij),(k))=A((i),(j),(k)):

A2=reshape(A,[size(A,1)*size(A,2),size(A,3)])

Then you do the usual multiplcation:

for all (ij) B2((ij))=sum_k A2((ij),(k))*v((k)):

B2=A2*v

The you reshape back:

B((i),(j))=B((ij))

B=reshape(B2,[size(A,1) size(A,2)])

I hope this is clear

like image 183
Oli Avatar answered Sep 22 '22 23:09

Oli


You can do it a bit smoother. for matrices reshape only requires 1 argument, the other one is figured out automatically if not specified, which is very useful in exactly such situations.

So, the solution presented by Oli can be more briefly written as

A = rand(2,3,4);
v = rand(4,1);

A2 = reshape(A, [], numel(v));      % flatten first two dimensions
B2 = A2*v;
B  = reshape(B2, size(A, 1), []);
like image 23
angainor Avatar answered Sep 23 '22 23:09

angainor