Elementwise Multiplication of column of 3D-array with an 1D-array
2 views (last 30 days)
Show older comments
Hi, I'm trying to multiply a column of an array with dimensions (3,5,3) with an 1D-array as follows:
B=rand(3,5,3);
k=0:2;
B(1,1,:).*k
Matlab tells me:
Error using .*
Matrix dimensions must agree.
However, the size of the column and the array is always 3. What's wrong with this expression?
Many thanks in advance.
0 Comments
Accepted Answer
Guillaume
on 3 Jun 2015
Edited: Guillaume
on 3 Jun 2015
A 1D vector of size [1, 1, 3] (your B(1, 1, :)) is not the same size as a 1D vector of size [1, 3, 1] (your k), even though they have the same number of elements. You either need to squeeze the singleton dimensions out of your B vector, permute the dimensions of k, or reshape either:
squeeze(B(1,1,:) .* k' %squeeze returns a column vector, so transpose k
B(1, 1, :) .* permute(k, [1 3 2]) %swap 2nd and 3rd dimension
reshape(B(1, 1, :), 1, []) .* k
B(1, 1, :) .* reshape(k, 1, 1, []) %same as permute effectively
0 Comments
More Answers (1)
the cyclist
on 3 Jun 2015
B(1,1,:) is a 1x1x3 array, and k is a 1x3 array, which could be considered a 1x3x1. Those are not actually the same.
You can use the permute function to rearrange the dimensions to get what you want.
0 Comments
See Also
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!