How to sum over indices i+j=k without using a for loop?
조회 수: 15 (최근 30일)
이전 댓글 표시
I have an matrix β and a vector n. I am trying to compute two sums:
(k is an integer). So I should have answers for and . Is there a way to compute these sums without using for loops or computationally expensive Matlab matrix manipulation functions? The first sum in particular is giving me a headache. Thanks!
댓글 수: 4
Jan
2021년 6월 18일
편집: Jan
2021년 6월 18일
@Jackie Taylor: What is vmax and nold? I try:
vol = 1:delv:kmax; % Instead of vmax
n = rand(p, r); % nold -> n
채택된 답변
Jan
2021년 6월 18일
편집: Jan
2021년 6월 18일
Because beta is determined inside the for i and for j loops, we can improve only the inner loops:
r = 501;
kmax = 501;
p = 60;
beta = rand(r, r);
n = rand(p, r);
qin = zeros(p, r);
qout = zeros(p, r);
i = 1;
tic
for rep = 1:100 % Only to get a more accurate time measurement, remove in real code!
for k = 1:kmax
for s = 1:k-1
qin(i,k) = qin(i,k) + beta(s,k-s) * n(i,s) * n(i,k-s);
end
for s = 1:r-k
qout(i,k) = qout(i,k) + beta(s,k) * n(i,s) * n(i,k);
end
end
end
toc
qin = zeros(p, r);
qout = zeros(p, r);
tic
ni = n(i, :);
for rep = 1:100
for k = 1:kmax
a = 0;
for s = 1:k-1
a = a + beta(s, k-s) * ni(s) * ni(k-s);
end
qin(i, k) = qin(i, k) + a;
a = 0;
for s = 1:r-k
a = a + beta(s, k) * ni(s);
end
qout(i, k) = qout(i, k) + a * ni(k);
end
end
toc
Almost 2 times faster with just avoiding some indexing. Because this is a part of the problem only the total speedup will be smaler. My trials to vectorize this are about 10 times slower. In addition the timings measure in the online version differ from a local version. So please check and post, if the modified version is faster at all.
추가 답변 (1개)
Walter Roberson
2021년 6월 18일
If you have i+j = k, then you start at row k-1, column 1 as the first point (if k >= the number of rows). The next point would be row k-2, column 2. The third point would be row k-3, column 3. And so on.
In terms of linear indices, the first one is (k-1) + rows*(1-1); the second one is (k-2)+rows*(2-1), the third is (k-3)+rows*(3-1) and so on. Those are k-1, k-2+rows, k-3+2*rows, k-4+3*rows and so on. The difference between those is [rows-1], [rows-1], [rows-1], [rows-1] and so on.
Therefore the linear indices are k-1:rows-1:SOME_ENDPOINT . And that can be implemented as a vector without using a loop.
You will need some logic for the case where k is less than the number of rows or columns.
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!