MATLAB Answers

Dot product not working for 2d matrix

33 views (last 30 days)
Kartik Kartik
Kartik Kartik on 21 Sep 2020 at 22:36
Commented: Vasishta Bhargava on 22 Sep 2020 at 1:35
I want dot product of two matrix of shape (1,2)(2,3) but when I try it using dot(A,B) it thows an error to make the dimension same.
I am new to matlb, started today. any help is appreciated.
Thanks,
Kartik

  0 Comments

Sign in to comment.

Accepted Answer

Vasishta Bhargava
Vasishta Bhargava on 21 Sep 2020 at 22:50
Edited: Vasishta Bhargava on 21 Sep 2020 at 22:58
Matrices must be of same size to perform dot product. size_of A must be same as _size of B. You have A = 2x1 and B as 3x2. If A = 2x1 then B should also have 2x1 I.e. 2 rows and 1 column

  3 Comments

Kartik Kartik
Kartik Kartik on 21 Sep 2020 at 23:03
Thanks for such a quick response vasishta. But we can multiply matrices with dimen mXn and nXm. why does it have to be same. what to do if I can not make them same and still want the multiplication.
Walter Roberson
Walter Roberson on 22 Sep 2020 at 0:31
Algebraic Matrix Multiplication ("inner product") of a m x n matrix A and an n x p matrix B is defined as
C(i,j) = dot(A(i,:), B(:,j).')
which is
C(i,j) = sum(A(i,:).*B(:,j).')
However, dot product of two matrices A, B is defined in MATLAB as
C(1,i) = dot(A(:,i), B(:,i))
which requires that the two arrays be the same size.
If you want to be able to do dot product of two matrices of different sizes, you are going to need to define how you want the output to be calculated.
For example if your 1 x 2 is A and your 2 x 3 is B, then do you want
dot( repmat(A.', 1, size(B,2)), B) %-> 1 x 3 result
dot( repmat(A, size(B,2), 1), B.') %-> 1 x 2 result
Vasishta Bhargava
Vasishta Bhargava on 22 Sep 2020 at 1:35
@Kartik. You mentioned about the general rule for matrix multiplication. The other option is to make A and B of same size as shown in Walter comment using repmat.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!

Translated by