Filter löschen
Filter löschen

how to multiply and concatenate at same time?

3 Ansichten (letzte 30 Tage)
Martin
Martin am 27 Apr. 2013
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

Akzeptierte Antwort

Cedric
Cedric am 27 Apr. 2013
Bearbeitet: Cedric am 27 Apr. 2013
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 Kommentare
Martin
Martin am 27 Apr. 2013
I write a separate function with this. Thanks, it helped...
Cedric
Cedric am 27 Apr. 2013
Bearbeitet: Cedric am 27 Apr. 2013
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.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Roger Stafford
Roger Stafford am 27 Apr. 2013
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,[]);

Kategorien

Mehr zu Creating and Concatenating Matrices finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by