MATLAB Answers

Vectorization of a specific matrix product

2 views (last 30 days)
Abolfazl Hashemi
Abolfazl Hashemi on 28 Jul 2016
Hi everyone. I have a code and I am having a hard time trying to vectorize it. I was wondering if anyone can help me. Here is the code:
I have these matrices
U=randn(n,k);
A=randn(n,m);
I would like to construct another matrix
T=randn(n,m);
such that
S=U'*A;
for j=1:m
T(:,j)=sum(U*diag(S(:,j)),2);
end
Any help is greatly appreciated.

  0 Comments

Sign in to comment.

Answers (1)

James Tursa
James Tursa on 2 Aug 2016
Edited: James Tursa on 2 Aug 2016
You could replace the for-loop by this:
T = reshape(sum(bsxfun(@times,U,reshape(S,1,k,m)),2),n,m);
But, I don't know what you mean by this statement since it doesn't affect anything other than set the size of T:
T=randn(n,m);

  3 Comments

Abolfazl Hashemi
Abolfazl Hashemi on 2 Aug 2016
Thank you so much. For that line, I just wanted to set the size for T.
James Tursa
James Tursa on 2 Aug 2016
OK. Since T is set directly with my posted code, you don't need to include this line for setting the size of T.
Abolfazl Hashemi
Abolfazl Hashemi on 3 Aug 2016
Thanks again! I was hopeless and when I saw you code I was really impressed.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!