简体   繁体   中英

How do I multiply 3 vectors and obtain a 3D matrix in MATLAB?

What I'm trying to do is obtain results like the snippet below without a loop.

x = [1 2 3 4];
y = [2 3 4];
z=[7 8];

[x'*y]

for k=1:size(z, 2)
z2(:,:,k)=[x'*y]*z(k);
end

z2

Loops may slow down MATLAB, however. How do I approach the task without them?

You can just do this because z is ` vector:

bsxfun(@times, reshape(z, 1, 1, []), [x'*y])

If z was a 2D matrix itself and you wanted to do a matrix multiplication at each level then you would need to use the links I posted in my comment. But because each time you are multiplying by a scalar, you can use @times .

Have a look here . Base on this, you could do as follows:

x = [1 2 3 4];
y = [2 3 4];
z=[7 8];


% replicate [x'*y] into 3D array.
d = repmat([x'*y], [1, 1, numel(z)])

% multiplay by z vector
z2 = bsxfun(@times, d, reshape(z,[1, 1, numel(z)]))

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM