フィルターのクリア

How to eliminate for-loop?

1 回表示 (過去 30 日間)
Andreas Schwager
Andreas Schwager 2016 年 7 月 27 日
コメント済み: Andreas Schwager 2016 年 8 月 1 日
Hi to everybody,
in the for-loop below, is a multiplication of a scalar with twice a matrix column. If two vectors in a for-loop are multiplied it should be possible to reformulate it into a matrix multiplication. How to do this? The task is to speed up the processing, especially if dimensions of matrix are becoming large.
A = [1 2; 3 4]
B = [5 6 7; 8 9 10; 11 12 13]
C = [1 0 0; 0 2 0; 0 0 0]
for indx = 1:size(A,2)
D(indx,:,:) = C(indx,indx) .* A(:,indx) * B(:,indx)';
end
Thanks Andy

採用された回答

Andrei Bobrov
Andrei Bobrov 2016 年 7 月 27 日
編集済み: Andrei Bobrov 2016 年 7 月 27 日
A = [1 2; 3 4];
B = [5 6 7; 8 9 10; 11 12 13];
C = [1 0 0; 0 2 0; 0 0 0];
n = size(A,2);
Cd = diag(C);
D = bsxfun(@times,A,reshape(Cd(1:n),1,[]));
D = bsxfun(@times,D,permute(B(:,1:n),[3,2,1]));
D = permute(D,[2,1,3]);
  2 件のコメント
Andreas Schwager
Andreas Schwager 2016 年 7 月 27 日
Dear Andrei,
thanks for this answer!
However, if I do:
clear A B C D E F Cd n
A = [1 2; 3 4];
B = [5 6 7; 8 9 10; 11 12 13];
C = [1 0 0; 0 2 0; 0 0 0];
D = zeros(size(A,2),size(A,2),size(B,2));
for indx = 1:size(A,2)
D(indx,:,:) = C(indx,indx) .* A(:,indx) * B(:,indx)';
end
n = size(A,2);
Cd = diag(C);
E = bsxfun(@times,A,reshape(Cd(1:n),1,[]));
F = bsxfun(@times,E,permute(B(:,1:n),[3,2,1]));
D - F
... there are a couple of non zero elements. Your code ignores the last column of B.
Thanks! Andy
Andrei Bobrov
Andrei Bobrov 2016 年 7 月 27 日
Thank you Stephen! I am corrected too.

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

その他の回答 (1 件)

Stephen23
Stephen23 2016 年 7 月 27 日
編集済み: Stephen23 2016 年 7 月 27 日
This gives the correct output, unlike the accepted answer:
>> N = size(A,2);
>> Cd = diag(C);
>> G = bsxfun(@times,A.',permute(B(:,1:N),[2,3,1]));
>> G = bsxfun(@times,Cd(1:N),G);
>> isequal(D,G)
ans = 1
  2 件のコメント
Andrei Bobrov
Andrei Bobrov 2016 年 7 月 27 日
+1
Andreas Schwager
Andreas Schwager 2016 年 8 月 1 日
Dear Stephen, Dear Andrei,
Thanks a lot for your support!

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

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by