Jakub
Jakub

Reputation: 3

MATLAB Matrix column subtraction

i am struggling with the following problem.

I have 2 matrices, let's say A and B which dimension can change in time and I want to create a new matrix C as follows:

I want to subtract all columns in matrix B from all columns in matrix A. So if for example matrix A was [1 2;5 6;8 5] and matrix B [2 2;2 1;3 5], then matrix C would be [1-2 1-2 2-2 2-2;5-2 5-1 6-2 6-1;8-3 8-5 5-3 5-5].

I have tried this code, but there's a mistake somewhere and I can't find it. Could you please correct the code so it works or provide a better solution to get the right result?

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

[m,n]=size(matrixA);
[o,p]=size(matrixB);

C = zeros(m,n*p);
for p = 1:n
  for q = 1:p
    C(:,3*p+q-3) = matrixA(:,p)-matrixB(:,q);
  end
end

Upvotes: 0

Views: 98

Answers (2)

Tommaso Belluzzo
Tommaso Belluzzo

Reputation: 23675

Your example with column-wise equally sized matrices is pretty easy to deal with:

matrixA = [1 2; 5 6; 8 5];
matrixB = [2 2; 2 1; 3 5];

A = repelem(matrixA,1,2);
B = repmat(matrixB,1,2);
C = A - B

C =
     -1    -1     0     0
      3     4     4     5
      5     3     2     0

But for handling mismatching column sizes too, things get a little bit more complex:

matrixA = [1 2; 5 6; 8 5];
matrixB = [2 2; 2 1; 3 5];

A = repelem(matrixA,1,size(matrixB,2));
B = repmat(matrixB,1,size(matrixA,2));
C = (B - A) .* -1

C =
    -1    -1     0     0
     3     4     4     5
     5     3     2     0

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

A = repelem(matrixA,1,size(matrixB,2));
B = repmat(matrixB,1,size(matrixA,2));
C = (B - A) .* -1

C =
     1    -2     0     2    -1     1
    -1    -4    -5     2    -1    -2
     5     8     7     2     5     4

Upvotes: 0

Luis Mendo
Luis Mendo

Reputation: 112679

I haven't looked into your code, but you can do it simpler and vectorized with permute, bsxfun, reshape:

A = [1 2;5 6;8 5];
B = [2 2;2 1;3 5];
C = reshape(bsxfun(@minus, permute(A, [1 3 2]), B), size(A,1), []);

From R2016b onwards bsxfun is not necessary:

C = reshape(permute(A, [1 3 2]) - B, size(A,1), []);

Upvotes: 3

Related Questions