Avoid for loops, use cell operation

1 回表示 (過去 30 日間)
Xh Du
Xh Du 2017 年 5 月 9 日
編集済み: Matt J 2017 年 5 月 10 日
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!
  2 件のコメント
Stephen23
Stephen23 2017 年 5 月 9 日
Xh Du
Xh Du 2017 年 5 月 9 日
Yes thank you, I was not sure whether continue editing that post or open a new post, then decided to open a new post as in the old one I could only comment.

サインインしてコメントする。

採用された回答

Matt J
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 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by