Home > Software design >  Analog to .* for tensor/ vector multiplications in matlab
Analog to .* for tensor/ vector multiplications in matlab

Time:02-02

I am generalizing a 1-D numerical method to 2-D and have run into an inconvenience. I was previously scaling each row in an array by using b.*A, where b is a (nx1) vector and A is an (nxm) array.

Is there a slick operation to extend this to a tensor? Let's say B is (nxm1xm2). When I try to sort out how to do b.*B I inevitably throw an "Array dimensions must match for binary array op." error.

I would rather use a builtin method of some kind or a cute way of mapping the multiplication function rather than brute forcing it with a for loop to keep the code clean and reasonably optimal.

To clarify

%I commonly use this product
A=[1,1,1;2,2,2;1,1,1];
b=[1;2;3];

b.*A

%I would like something similar to this which would multiply b(i) with B(:,:,i)
B=zeros(2,2,3);

B(:,:,1)=1;
B(:,:,2)=1;
B(:,:,3)=1;

b.*B

Outputs

ans =

     1     1     1
     4     4     4
     3     3     3

Array dimensions must match for binary array op.

Error in script4question (line 14)
b.*B
 

Thanks in advance for your time.

Nick

CodePudding user response:

You need to make the sizes match in each dimension. This means that the size in each dimension needs to be either the same as in the other array, or 1. In the latter case implicit expansion replicates the array with size 1 along that dimension as needed.

In your example, b is 3×1(×1) and B is 2×2×3, so their sizes don't match. To achieve what you want you need to turn b into a 1×1×3 vector, using either permute, shiftdim or reshape:

reshape(b, 1, 1, []).*B

For Matlab versions older than R2016b there is no implicit expansion. In that case you can obtain the same result using bsxfun:

bsxfun(@times, reshape(b, 1, 1, []), B)
  •  Tags:  
  • Related