Search code examples
matlabmatrixsubtraction

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

Solution

  • 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), []);