vector to repeated matrix multiplication

조회 수: 9 (최근 30일)
Fred
Fred 2011년 2월 22일
Hi all.
Just wanted to find a non loop way of computing the following operation.
A = [1 2; 3 4], V = [ 1 2 3]
compute Y = 1*A + 2*A + 3*A = 1*[1 2; 3 4] + 2*[1 2; 3 4] + 3*[1 2; 3 4] = [6 12; 18 24]
i.e. each element of V times A then sum up each of these matrices
many thanks!

채택된 답변

Matt Fig
Matt Fig 2011년 2월 22일
One approach:
sum(bsxfun(@times,A,reshape(V,1,1,3)),3)
  댓글 수: 1
Fred
Fred 2011년 2월 22일
Thank you Matt! Works out!

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

추가 답변 (5개)

Matt Tearle
Matt Tearle 2011년 2월 22일
Not being able to think up a more elegant solution off the top of my head, how about
reshape(repmat(A(:),1,3)*(V'),2,2)
Or, more generally and cryptically,
reshape(repmat(A(:),size(V))*(V'),size(A))
  댓글 수: 1
Fred
Fred 2011년 2월 22일
Hi Matt, Many Thanks! Seems like for than one way to skin a cat.

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


Bruno Luong
Bruno Luong 2011년 2월 22일
v1 = [1 2 3]
v2 = [4 5 6]
A = [1 2; 3 4]
v2(2,:) = -1
P=sum(bsxfun(@times,v1,v2),2)
P(1)+P(2)*A % *Not* polynomial of A

Fred
Fred 2011년 2월 22일
OK, one last one which is just an extension of this one.
suppose I have v1 = [1 2 3], v2 = [4 5 6], and A = [1 2; 3 4]
I want to eliminate a loop, bottleneck in my code of course :) so want to from the following
1*(4 - A) + 2*(5 - A) + 3*(6 - A) = [26 20; 14 8]
many thanks!
Cheers, Fred

Fred
Fred 2011년 2월 22일
actually, figured it out. Thank you both again for your help!
A1 = bsxfun(@minus,reshape(v2,1,1,3),A);
sum(bsxfun(@times,reshape(v1,1,1,3),A1),3);
a similar method can be used with the repmat command like matt posted above. BTW, which is faster? repmat bs bsxfun?
Cheers, Fred
  댓글 수: 4
Fred
Fred 2011년 2월 22일
Hi Matt, can you give an example of indexing for this problem? I am not familiar with it.
Matt Fig
Matt Fig 2011년 2월 22일
Sure, see below.

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


Matt Fig
Matt Fig 2011년 2월 22일
On my machine, this outputs: 3.1 2.2 1
function [] = compare_bsx()
% Compare BSXFUN, REPMAT and indexing.
T = [0 0 0];
N = 40; % The array sizes. Change this to see if the fastest changes
% with array size. It will.
for ii = 1:300
mA = ceil(rand*N); % Make the arrays up to size N.
nA = ceil(rand*N);
nV = ceil(rand*N);
A = round(rand(mA,nA)*100);
V = round(rand(1,nV)*100);
tic
E = sum(bsxfun(@times,A,reshape(V,1,1,length(V))),3);
T(1) = T(1) + toc;
tic
E2 = reshape(repmat(A(:),size(V))*(V'),size(A));
T(2) = T(2) + toc;
tic
E3 = A(:);
E3 = E3(:,ones(length(V),1,'single'));
E3 = reshape(E3*(V.'),size(A));
T(3) = T(3) + toc;
end
T/min(T) % The 1 is the quickest
  댓글 수: 1
Fred
Fred 2011년 2월 22일
wow! 2 or 3x's faster! I'll give it a go. Many thanks again!

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

카테고리

Help CenterFile Exchange에서 Resizing and Reshaping Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by