how to multiply and concatenate at same time?

2 次查看(过去 30 天)
Dear Matlab guys, I am wondering how to "multiply and concatenate" at same time? Let me write a simple example:
a = [ a b c ; d e f ]
b = [ g h ; i j ]
my idea is to arrive at this:
c = [ ag ah bg bh cg ch ; di dj ei ej fi fj ]
To present it this way I was thinking about the so-called Kronecker product, however I do not think that is the right thing though, since it create hugher matrix. For-loops is possible to do it, but I search for an easier way, - if it exists ?...
thanks in advance, -best Martin B

采纳的回答

Cedric
Cedric 2013-4-27
编辑:Cedric 2013-4-27
Kronecker product would be suitable if we could apply it along a given dimension, but it seems that we can't. As an alternative, look at the following and let me know if there is anything that you don't understand:
>> A = [1, 2, 3; 4, 5, 6] ;
>> B = [7, 8; 9, 10] ;
>> C = reshape(repmat(A, size(B,2), 1), size(A,1), []) .* repmat(B, 1, size(A,2))
C =
7 8 14 16 21 24
36 40 45 50 54 60
  3 个评论
Martin
Martin 2013-4-27
I write a separate function with this. Thanks, it helped...
Cedric
Cedric 2013-4-27
编辑:Cedric 2013-4-27
I don't think that there is a completely trivial way to do it, as it's not a standard operation. Roger proposed another way below, but I don't think that you will find it any simpler.
To understand my answer, evaluate
reshape(repmat(A, size(B,2), 1), size(A,1), [])
and
repmat(B, 1, size(A,2))
and observe that the element-wise product ( .* ) between these two arrays is what you want to do. Also, observe the structure of each one of these arrays, and you'll understand the explanation below.
As you can see, the only thing that we have to do with B is to repeat it "horizontally" a number of times that corresponds to the number of columns in A. We do this using REPMAT.
It is a bit more complicated for A as we have to repeat each of its columns a number of time that corresponds to the number of columns in B. This can be achieved by repeating it "vertically" this number of times, and reshaping the result.

请先登录,再进行评论。

更多回答(1 个)

Roger Stafford
Roger Stafford 2013-4-27
A method using 'bsxfun':
A = [ a b c ; d e f ];
B = [ g h ; i j ];
[m,n] = size(A);
C = reshape(bsxfun(@times,reshape(A,[m,1,n]),B),m,[]);

类别

Help CenterFile Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by