필터 지우기
필터 지우기

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

조회 수: 1 (최근 30일)
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.

채택된 답변

Azzi Abdelmalek
Azzi Abdelmalek 2014년 8월 7일
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,[]))
  댓글 수: 2
Joe
Joe 2014년 8월 7일
OK thank you let me check this out with my code
Joe
Joe 2014년 8월 7일
Thank you Azzi you totally killed it and are a gentleman and a scholar. Works perfectly.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by