Search code examples
matlabmatrixmultidimensional-arraymatrix-multiplicationmultiplication

How to multiply matrix having different size (without knowing exactly the size they will have)?


I have to multiply 2 matrices (scalar multiplication) that have different sizes. For instance, the 1st has size n-by-m and the 2nd n+1-by-m+1. The fact is that it is not always the case. I mean, sometimes the first has size n+1-by-m+1 and the 2nd n-by-m or n+2-by-m+2 etc...

Example:

a = [ 1 2 3; 
      4 5 6]; 

b = [ 1 2 3; 
      4 5 6; 
      7 8 9]

I would like Matlab to check the size of each matrix, then multiply them using the smallest size available between the 2 i.e. ignoring the last rows and columns of the bigger matrix (or similarly, adding rows and columns of 0 to the smaller matrix).

With the example inputs I would like to obtain:

c = [1  4  9; 
     16 25 36] 

or

c = [1  4  9; 
     16 25 36; 
     0  0  0]

How can I write this?


Solution

  • Find the number of rows and columns of your final matrix:

    n = min(size(a,1), size(b,1));
    m = min(size(a,2), size(b,2));
    

    Then extract only the relevant sections of a and b (using the : operator) for your multiplication:

    c = a(1:n,1:m).*b(1:n,1:m)