Vectorization in cell array assignment without nested for loop
2 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
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 comentarios
Respuestas (1)
Andrei Bobrov
el 25 de Ag. de 2016
Editada: Andrei Bobrov
el 25 de Ag. de 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 comentarios
Ver también
Categorías
Más información sobre Loops and Conditional Statements en Help Center y File Exchange.
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!