Home > Software design >  How do I subtract every row of a matrix with every row of a second matrix in matlab?
How do I subtract every row of a matrix with every row of a second matrix in matlab?

Time:11-04

I have two matrices A (51 rows X 5100 columns) and B (51rows X 5100 columns) and I want to subtract every row of A with every row of B to obtain another matric C (2601 rows X 5100 columns). How can I have the matrix C?

CodePudding user response:

You can do that by

  1. permuting the matrices' dimensions to obtain 3D arrays of size (in your example) 51 × 1 × 5100 and 1 × 51 × 5100 respectively;
  2. subtracting with implicit expansion, which gives an array of size 51 × 51 × 5100;
  3. reshaping to collapse the first two dimensions into one, which gives the final 51^2 × 5100 matrix.
A = rand(51, 5100); % example matrix
B = rand(51, 5100); % example matrix, same number of columns
C = reshape(permute(A, [1 3 2]) - permute(B, [3 1 2]), [], size(A, 2));

CodePudding user response:

The crux of the problem lies in getting the correct pairs of rows for both matrices. To do this, you could use the meshgrid() function to generate a matrix that varies from 1:n along its rows, and another that varies along its columns (where n is the number of rows).

For example:

mtx1 = reshape(1:9, 3, 3);
mtx2 = reshape(101:109, 3, 3);
n1 = size(mtx1, 1);
n2 = size(mtx2, 1);

[r1, r2] = meshgrid(1:n1, 1:n2);

This gives:

r1 =

   1   2   3
   1   2   3
   1   2   3

r2 =

   1   1   1
   2   2   2
   3   3   3

Next, flatten both r1 and r2:

f1 = r1(:)
f2 = r2(:)

Now, we have:

f1 =

   1
   1
   1
   2
   2
   2
   3
   3
   3

f2 =

   1
   2
   3
   1
   2
   3
   1
   2
   3

We can use f1 and f2 as the indices for our pairs of rows:

mtx1(f1, :) repeats the first row of mtx1 three times, then the second row, then the third row

mtx1(f1, :)

   1   4   7
   1   4   7
   1   4   7
   2   5   8
   2   5   8
   2   5   8
   3   6   9
   3   6   9
   3   6   9

mtx2(f2, :) repeats the entire matrix mtx2 three times

mtx2(f2, :)


   101   104   107
   102   105   108
   103   106   109
   101   104   107
   102   105   108
   103   106   109
   101   104   107
   102   105   108
   103   106   109

Subtract these two, and you get your pairwise difference of rows:

mtx2(f2, :) - mtx1(f1, :)

   100   100   100
   101   101   101
   102   102   102
    99    99    99
   100   100   100
   101   101   101
    98    98    98
    99    99    99
   100   100   100

This also works when mtx1 and mtx2 have different row counts.

  • Related