Matrix column subtraction problem

I know this is really basic stuff but unfortunately I can't get to the right solution.
I have for example these 2 matrices:
matrixA=[1 5;5 2;0 0;3 2;3 6]
and
matrixB=[4 5 6;8 5 2;3 3 2;1 2 1;2 5 4]
What I want to do is to subtract all columns in matrixB from column 1 and column 2 respectively in matrixA. So I want to make
matrixC=[1-4 1-5 1-6 5-4 5-5 5-6;5-8 5-5 5-2 2-8 2-5 2-2;....;....;.....]

 Accepted Answer

Roger Stafford
Roger Stafford on 11 Mar 2018
Edited: Roger Stafford on 11 Mar 2018
C = zeros(5,2*3);
for p = 1:2
for q = 1:3
C(:,3*p+q-3) = A(:,p)-B(:,q);
end
end
Or this:
C = reshape(repmat(reshape(A,5,1,2),1,3,1)-repmat(reshape(B,5,3,1),1,1,2),5,[]);

4 Comments

This works in older version of MATLAB but now I am trying to modify the code in a way so it can be used for matrices of any size as the size of matrixA and matrixB can change in time.
I tried this, but still can't get the right solution. Could you tell me where I am doing a mistake?
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
You can use 3D indexing for your assignment, and reshape() afterwards.
@Jakub: For matrices A and B of general size:
[m,n1] = size(A);
n2 = size(B,2); % size(B,1) must also be m
C = reshape(repmat(reshape(A,m,1,n1),1,n2,1)-repmat(reshape(B,m,n2,1),1,1,n1),m,[]);

Sign in to comment.

More Answers (1)

[matrixA(:,1)-matrixB,matrixA(:,2)-matrixB]
This might require R2016b or later.

2 Comments

Thanks, is there any other solution for older versions of MATLAB?
cell2mat(arrayfun(@(COLIDX) bsxfun(@minus, matrixA(:,COLIDX), matrixB), 1:size(matrixA,2), 'uniform', 0))

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!