Vectorization in cell array assignment without nested for loop
조회 수: 2 (최근 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?
댓글 수: 0
답변 (1개)
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));
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!