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
댓글 수: 0
채택된 답변
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
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
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 Center 및 File Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!