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!
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
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), []);
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