Vectorising Multiplying each column from a matrix with a square matrix and the tranpose of this column

조회 수: 1 (최근 30일)
Hello,
I have an operation that I'm doing with a loop but would like to vectorise if possible.
I have a matrix h (2790x3591) and a matrix Pn(2790x2790).
I need to implement the following operation: h_column' * Pn * h_column, for all columns of h.
Is there a way to vectorise this operation? It takes about 45s to do with the for loop.
NB: The matrices are complex with very small imaginary parts, so that adds a bit of delay because the multiplications are more involved.

답변 (3개)

Kevin Holly
Kevin Holly 2022년 2월 23일
Can you do the following?
h = rand(2790,3591);
Pn = rand(2790,2790);
size(h'*Pn*h)
ans = 1×2
3591 3591

James Tursa
James Tursa 2022년 2월 23일
If you need the same column on each side of the multiply, then maybe this:
result = sum(h'*Pn.*h',2);
  댓글 수: 2
Kleanthis-Marios Papadopoulos
Kleanthis-Marios Papadopoulos 2022년 2월 23일
편집: Kleanthis-Marios Papadopoulos 2022년 2월 23일
I don't need the same column on each side because the operation is column of h' (turn it into row)*Pn* h.
This isn't what I'm looking for, although it is close.
Matt J
Matt J 2022년 2월 23일
편집: Matt J 2022년 2월 23일
I need to take diag(h'*Pn*h).
No, that will be super slow and inefficient. This should be what you want,
result = sum(h.*(Pn*h),1);
James' version was almost equivalent except for a missing transpose,
result = sum(h'*Pn'.*h',2);
but no need to incur the expense of all those transpositions, as far as I can see.

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


Jan
Jan 2022년 2월 23일
편집: Jan 2022년 2월 24일
Then please post you code. It is much faster on my computer:
h = rand(2790, 3591);
Pn = rand(2790, 2790);
tic
R = zeros(1, 3591);
for k = 1:3591
R(k) = h(:, k).' * Pn * h(:, k);
end
toc
Elapsed time is 8.494673 seconds.
tic % Matt J and James:
R2 = sum(h'*Pn'.*h',2);
toc
Elapsed time is 0.508067 seconds.
  댓글 수: 1
Kleanthis-Marios Papadopoulos
Kleanthis-Marios Papadopoulos 2022년 2월 23일
This operation is part of a function which is part of another function, so the code here on its own won't make much sense.
This is the snippet that I'm concerned about
for j=1:Nsc
hj= findhVectorised(theta,l_ik,uk,J,Fjvec(j),Nsc,array,userpn);
holderonj=[holderonj;hj];
%dotp=[dotp; hj.*conj(hj)];
%numer=[numer; sum(dotp)]
numer(j,:)=sum(hj.*conj(hj),1);
% for iter=1:length(hj)
% den(j,iter)= hj(:,iter)'*Pn*hj(:,iter);
% end
% den2= hj'*Pn*hj;
temp=diag(hj'*Pn*hj);
temp=transpose(temp);
den(j,:)=temp;
end

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

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

제품


릴리스

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by