Avoid for loops, use cell operation

1 次查看(过去 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!
  2 个评论
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 CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by