HXSP1947
HXSP1947

Reputation: 1351

add vector to multi dimensional array matlab

Thanks in advance for the help.

Suppose I have a multi D array x such that

x(:,:,1) = [1 2; 3 4];
x(:,:,2) = [5 6; 7 8];

and a matrix y such that

y = [1 2; 5 6];

I would like to add the first row of y to each row of x(:,:,1) and the second row of y to each element of x(:,:,2). This will produce an array z such that

z(:,:,1) = [2 4; 4 6];
z(:,:,2) = [10 12; 12 14];

In reality (not the example I am giving) I would like to do this operation on a very large multi D array x and a very large matrix y. I therefore want to do this as efficiently as possible.

The naive approach would be to use for loops to do this, but this would not be efficient what-so-ever. I believe that an efficient approach would be to incorporate bsxfun to accomplish this, but I haven't been able to figure out an approach. y and x can and be restructured to accomplish this task as long as the same z is produced and, most importantly, the amount of time needed to build z is less than the for loop approach.

I was able to find this which does what I want, but only for multiplication and not summation. I could modify this code to do what I want but I feel as though with summation that there has to be a simpler approach.

Upvotes: 1

Views: 74

Answers (1)

Luis Mendo
Luis Mendo

Reputation: 112659

You just need bsxfun and a little bit of permute:

z = bsxfun(@plus, x, permute(y, [3 2 1]));

The key is to properly rearrange the dimensions of y so that the singleton expansion performed by bsxfun gives you the desired result.

Upvotes: 3

Related Questions