Reputation: 935
I have a matrix A
of size p x p
and a vector y = [y1,y2,...,yn]
.
What do I want to do is to create a 3 dimensional matrix of size p x p x n
, that is, it contains n
bands where each one is of size p x p
.
How each band is created?:
Each band is equal to the matrix A
multiplied by one value in y
. For example, the first band is A * y1
, the second band is A * y2
. On the other hand, the band number i
, where i = 1, ..., n
, is equal to A * yi
Well, this can be easily done using a for loop, but this is trivial and expensive in computation. How can I prevent using a for loop? Is there any very fast automatic method that can directly create the 3-D matrix?
Any help will be very appreciated.
Upvotes: 0
Views: 85
Reputation: 65430
You can use bsxfun
to multiply your p x p
matrix by each value in y
. We must reshape y
to be 1 x 1 x n
though so that the multiplication creates a third dimension.
out = bsxfun(@times, A, reshape(y, 1, 1, []));
If you're on R2016b or newer (when MATLAB introduced implicit broadcasting), you can replace bsxfun
with simply .*
out = A .* reshape(y, 1, 1, []);
Upvotes: 2