Avoid for loops, use cell operation
조회 수: 4 (최근 30일)
이전 댓글 표시
Hi all,
I've asked this question before but didn't get satisfied answer, so I'll change the way of asking.
Say I have an operation like this:
a = [3 8];
aTa = a' * a;
>> aTa
aTa =
9 24
24 64
Then in another case I have to decompose a into 2 cells "al, ar" by 3 = 1*3 and 8 = 2*4, in order to get the same result as aTa, I have to do:
al = {1 2};
ar = {3 4};
aTa1 = zeros(2, 2);
for i = 1:2
for j = 1:2
l1 = al{1, j};
l2 = al{1, i};
r1 = ar{1, j};
r2 = ar{1, i};
aTa1(i, j) = aTa1(i, j) + r2' * r1 * l1' * l2;
end
end
My question is, obviously the second operation (loops and r2' * r1 * l1' * l2) is much more complicated than first one (a' * a). If I have to decompose a, is there a faster, more compact way to obtain aTa1? Will it be faster if avoid using for loops but use some cell operation instead?
Tried this does not work, only get diagonal elements:
ata1 = cellfun(@(l1, l2, r1, r2) r2' * r1 * l1' * l2, al, al, ar, ar, 'un', 0);
Many thanks!
채택된 답변
Matt J
2017년 5월 9일
편집: Matt J
2017년 5월 10일
My question is, obviously the second operation (loops and r2' * r1 * l1' * l2) is much more complicated than first one (a' * a).
No, it is not. The second operation, assuming these are all row vectors, can be rewritten,
s=(r1 * l1'); %a scalar
aTa = s*(r2'*l2)
So, the operations are really just the same kind of outer products a*a' that you were considering originally, but with post-scaling.
If I have to decompose a, is there a faster, more compact way to obtain aTa1? Will it be faster if avoid using for loops but use some cell operation instead?
All cell operations use for loops internally. There is no "avoiding" loops by using cell arrays. Like those who responded to your previous post, I think you are barking up the wrong tree. I suspect the whole thing can be done most efficiently using numeric arrays.
댓글 수: 0
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!