Filter löschen
Filter löschen

Avoid for loops, use cell operation

4 Ansichten (letzte 30 Tage)
Xh Du
Xh Du am 9 Mai 2017
Bearbeitet: Matt J am 10 Mai 2017
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 Kommentare
Xh Du
Xh Du am 9 Mai 2017
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.

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Matt J
Matt J am 9 Mai 2017
Bearbeitet: Matt J am 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.

Weitere Antworten (0)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by