フィルターのクリア

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 Center および File ExchangeMatrix Indexing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by