Modify and speed up a for loop

2 次查看(过去 30 天)
Stef Fets
Stef Fets 2019-10-29
Hi everyone,
Do you have some idea on how to modify and speed up this for loop?
N usually is among 10 and 100, while K is of the order of 10^4. Moreover, u is an N x K matrix and kernel_vect is a K x 1 vector.
Thanks!
Kernel_appo = zeros(N^2,1);
for k=1:K
Mat_appo = (u(:,k)*u(:,k)');
Kernel_appo = Kernel_appo + kernel_vect(k)*Mat_appo(:);
end
  1 个评论
Adam
Adam 2019-10-29
Depending how big k is you can potentially pull out the Mat_appo line similar to the following logic:
u = reshape( 1:20, [4 5] ) % Some small test data - K = 5
Mat_appo = u .* reshape( u', [1 5 4] );
Mat_appo = reshape( permute( Mat_appo, [1 3 2] ), 4^2, [] );
then you should end up with what you have as Mat_appo(:) as the columns of the Mat_appo matrix above.
You can probably simplify those reshsapes and permutes too, that's just how I happened to get to the answer, which usually just involves some trial and error reshaping and permuting rather than working out the absolutely neatest way!

请先登录,再进行评论。

回答(1 个)

Cyrus Tirband
Cyrus Tirband 2019-10-29
编辑:Cyrus Tirband 2019-10-29
The last line can be brought outside the loop like so
Mat_appo = zeros(N,N,K);
for k=1:K
Mat_appo(:,:,k) = (u(:,k)*u(:,k)');
end
Kernel_appo=reshape(Mat_appo,N^2,[])*kernel_vect(:);
Since K is much larger than N, I reckon it would be faster to rewrite the for loop as follows:
Mat_appo = zeros(N,N,K);
for i = 1:N
for j = 1:N
Mat_appo(i,j,:) = u(i,:)*u(j,:);
end
end
Kernel_appo=reshape(Mat_appo,N^2,[])*kernel_vect(:);
I haven't tested it, but this code should be equivalent to yours and also faster.
  2 个评论
Stef Fets
Stef Fets 2019-10-29
Hi Cyrustd,
Thanks for your answer, but I don’t understand well it…
Maybe I should specify that u is an N x K matrix and kernel_vect is a k x 1 vector. All the quantities are real numbers.
Cyrus Tirband
Cyrus Tirband 2019-10-29
Does the code not run for you? It should do the exact same as your code. It first generates an N x N x K matrix for Mat_appo where the kth N x N matrix is the outerproduct of the kth u vector.
Then, it rearranges Mat_appo to a N^2 x K matrix and does a matrix multiplication with kernel_vect (which is K x 1), the result is a N^2 x 1 matrix called Kernel_appo.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by