Clear Filters
Clear Filters

Subtracting Matrices of Different Sizes by subtracting A(1) from all of B for all of A

1 view (last 30 days)
Hello,
I have been reading a lot about sbxfun, and it ALMOST does what I want it to do.
Let's say I have two matrices
A = [1 2 3
4 5 6
7 8 9];
B = [1 2 3 4
5 6 7 8
9 10 11 12];
I want to take A(1,1) and subtract it from EVERY element in B and store this in C. Then I want to move on to A(1,2) and subtract it from EVERY element in B and store this in C. In the end I would get (if I used A(1,1) and A(1,2) to subtract from B):
C(:,:,1) = [0 1 2 3
4 5 6 7
8 9 10 11];
C(:,:,2) = [-1 0 1 2
3 4 5 6
7 8 9 10];
etc...
I have tried sbxfun by adding some zeros to A to make it the same size as B, reshaping A into a 3d matrix and then sbxfun(@minus)-ing the now two equal size matrices, but this only takes row 1 of A and subtracts it from rows 1, 2, and 3 of B. It does not subtract EACH element of row 1 of A from EACH element of B.
I currently use a for loop to do this, but it take up a lot of computing power to do this, as my matrices are quite large. Is there a function that would do this for me and speed things up?
Thanks ahead of time.

Accepted Answer

Azzi Abdelmalek
Azzi Abdelmalek on 7 Aug 2014
A = [1 2 3
4 5 6
7 8 9];
B = [1 2 3 4
5 6 7 8
9 10 11 12]
D=A'
C=bsxfun(@minus, B,reshape(D(:),1,1,[]))

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!