Vectorization in cell array assignment without nested for loop
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
I have c being a large sparse matrix computed before and want to assign value to cell array D by using the outer product of c columns. However, I have to implemented special rules and cannot get outer product of same c columns.
From column 1 using the first for loop, I have to implemented another for loop and an if-else statement to skip the same index assignment by flagging.
Eventually, after the nested for loop, I want to add up all the G in one loop to get a matrix K. I add this 100 times.
c = rand(100,100);G = cell(1,100);
G{1} = eye(100);
for i = 1:100
flag = false;
for z = 2 :100
j = z-1;
if j == i
flag = true;
end
if flag == true
G{z} = (c(:,j+1)*c(:,i)');
else
G{z} = (c(:,j)*c(:,i)');
end
end
for z = 2 : 100
K = K + G{z}';
end
end
By using array I can reduce to a first layer of loop only. But i need multiple loops, is there a smarter way to do this?
0 Kommentare
Antworten (1)
Andrei Bobrov
am 25 Aug. 2016
Bearbeitet: Andrei Bobrov
am 25 Aug. 2016
n = size(c,2);
[jj,ii] = ndgrid(1:n-1,1:n);
ij = [ii(:),jj(:)];
t = diff(ij,1,2) == 0;
ij(t,2) = ij(t,2) + 1;
G = bsxfun(@times,c(:,ij(:,1)), permute( c(:,ij(:,2)),[3,2,1]));
K = squeeze(sum(G,2));
0 Kommentare
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Produkte
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!