Avoid for loops, use cell operation
4 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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!
Réponse acceptée
Matt J
le 9 Mai 2017
Modifié(e) : Matt J
le 10 Mai 2017
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 commentaires
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!