Vectorization in cell array assignment without nested for loop

1 次查看(过去 30 天)
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?

回答(1 个)

Andrei Bobrov
Andrei Bobrov 2016-8-25
编辑:Andrei Bobrov 2016-8-25
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));

类别

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