I have a matrix A
of size pxp
and a vector y = [y1,y2,...,yn]
.
What do I want to do is to create a 3 dimensional matrix of size pxpxn
, that is, it contains n
bands where each one is of size pxp
.
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.
You can use bsxfun
to multiply your pxp
matrix by each value in y
. We must reshape y
to be 1 x 1 xn
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, []);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.