Any tips for bsxfun and repeated calculation?

4 ビュー (過去 30 日間)
Marie
Marie 2017 年 10 月 29 日
コメント済み: Cedric 2017 年 10 月 30 日
Hello,
I am currently using bsxfun to subtract the first column from matrix A from matrix A itself, which is straightforward. C=bsxfun(@minus,A,B); Say A= [1 2 3; 3 4 1; 1 5 7] and B = [1 3 1]'
I want to do the same for each column and separately stack up the output vertically one matrix after another. In this example, the resulting matrix would thus be:
D= [0 1 2; 0 1 -2; 0 4 6; -1 0 1; -1 0 -3; -4 0 2; -2 -1 0; 2 3 0; -6 -2 0]
Thanks in advance for any advice.

採用された回答

Cedric
Cedric 2017 年 10 月 29 日
編集済み: Cedric 2017 年 10 月 29 日
If you have MATLAB R2016b or above, BSXFUN was replaced by automatic expansion and you can do it as follows:
>> D = repmat( A, 3, 1 ) - A(:)
D =
0 1 2
0 1 -2
0 4 6
-1 0 1
-1 0 -3
-4 0 2
-2 -1 0
2 3 0
-6 -2 0
otherwise, almost the same as your first solution:
>> D = bsxfun( @minus, repmat( A, 3, 1 ), A(:) ) ;
Both are based on the fact that indexing A linearly will read it column first:
>> A(:)
ans =
1
3
1
2
4
5
3
1
7
  2 件のコメント
Marie
Marie 2017 年 10 月 30 日
Thank you for the clear reply; much appreciated!
Cedric
Cedric 2017 年 10 月 30 日
My pleasure!

サインインしてコメントする。

その他の回答 (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