从两个2维矩阵创建3维矩阵 [英] Create a 3-dim matrix from two 2-dim matrices

查看:225
本文介绍了从两个2维矩阵创建3维矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经有一个N_1 x N_2矩阵A和一个N_2 x N_3矩阵B.

I already have a N_1 x N_2 matrix A, and a N_2 x N_3 matrix B.

我想创建一个N_1 x N_2 x N_3矩阵C,例如C(i,j,k) = A(i,j)*B(j,k).

I want to create a N_1 x N_2 x N_3 matrix C, such that C(i,j,k) = A(i,j)*B(j,k).

我想知道是否可以使用某些Matlab操作创建C,而不是逐个元素地创建它?

I was wondering if it is possible to create C using some Matlab operation, instead of doing it element by element?

推荐答案

您可以使用bsxfun与OP的答案做相同的事情(实际上在内部使用类似的方法,但是更干净一些):

You can do the same thing as the OP's answer using bsxfun (which actually works internally using a similar method, but is a little bit cleaner):

C = bsxfun(@times, A, permute(B, [3 1 2]));

这也要快很多(bsxfun必须在内部做一些魔术-可能利用了MATLAB的内部能力来使用多个线程进行某些操作,或者可能只是排列较小的矩阵要快得多,或类似因素的组合):

This is also quite a bit faster (bsxfun must do some magic internally - probably takes advantage of MATLAB's internal ability to do certain operations using multiple threads, or it might just be that permuting the smaller matrix is a lot faster, or some combination of similar factors):

>> N1 = 100; N2 = 20; N3 = 4; A = rand(N1, N2); B = rand(N2, N3);
>> tic; for n = 1:10000; C = repmat(A, [1, 1, size(B, 2)]) .* permute(repmat(B, [1, 1, size(A, 1)]), [3, 1, 2]); end; toc
Elapsed time is 2.827492 seconds.
>> tic; for n = 1:10000; C2 = bsxfun(@times, A, permute(B, [3 1 2])); end; toc
Elapsed time is 0.287665 seconds.

编辑:将permute移到repmat内可以节省一些时间,但仍远不及bsxfun:

moving the permute inside the repmat shaves a little bit of time off, but it's still nowhere near as fast as bsxfun:

>> tic; for n = 1:10000; C = (repmat(A, [1 1 size(B, 2)]) .* repmat(permute(B, [3 1 2]), [size(A, 1) 1 1])); end; toc
Elapsed time is 2.563069 seconds.

这篇关于从两个2维矩阵创建3维矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆