フィルターのクリア

Vectorization in cell array assignment without nested for loop

1 回表示 (過去 30 日間)
K.E.
K.E. 2016 年 8 月 25 日
編集済み: Andrei Bobrov 2016 年 8 月 25 日
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 Center および File ExchangeLoops and Conditional Statements についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by