quasoft
quasoft

Reputation: 5438

How to multiply two vectors with different length

Let's say I have two vectors:

A = [1 2 3];

B = [1 2];

And that I need a function similar to multiplication of A*B to produce the following output:

[
  1 2 3
  2 4 6
]

It seems that things like A*B, A*B' or A.*B are not allowed as the number of elements is not the same.

The only way I managed to do this (I am quite new at MATLAB) is using ndgrid to make two matrices with the same number of elements like this:

[B1,A1] = ndgrid(B, A);
B1.*A1

ans =
 1     2     3
 2     4     6

Would this have good performance if number of elements was large? Is there a better way to do this in MATLAB?

Actually I am trying to solve the following problem with MATLAB:

t = [1 2 3]

y(t) = sigma(i=1;n=2;expression=pi*t*i)

Nevertheless, even if there is a better way to solve the actual problem in place, it would be interesting to know the answer to my first question.

Upvotes: 2

Views: 21111

Answers (1)

nispio
nispio

Reputation: 1744

You are talking about an outer product. If A and B are both row vectors, then you can use:

A'*B

If they are both column vectors, then you can use

A*B'

The * operator in matlab represents matrix multiplication. The most basic rule of matrix multiplication is that the number of columns of the first matrix must match the number of rows of the second. Let's say that I have two matrices, A and B, with dimensions MxN and UxV respectively. Then I can only perform matrix multiplication under the following conditions:

A = rand(M,N);
B = rand(U,V);

A*B    % Only valid if N==U (result is a MxV matrix)
A'*B   % Only valid if M==U (result is a NxV matrix)
A*B'   % Only valid if N==V (result is a MxU matrix)
A'*B'  % Only valid if V==M (result is a UxN matrix)

There are four more possible cases, but they are just the transpose of the cases shown. Now, since vectors are just a matrix with only one non-singleton dimension, the same rules apply

A = [1 2 3]; % (A is a 1x3 matrix)
B = [1 2];   % (B is a 1x2 matrix)

A*B    % Not valid!
A'*B   % Valid.     (result is a 3x2 matrix)
A*B'   % Not valid!
A'*B'  % Not valid!

Again, there are four other possible cases, but the only one that is valid is B'*A which is the transpose of A'*B and results in a 2x3 matrix.

Upvotes: 6

Related Questions