Parallel two for loops
이전 댓글 표시
I am trying to perform a calculation for two for loops
parfor j = 1:25
for k = 1:5
A(:,j) = k;
end
end
A
I need answer like
1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5
instead of
5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5
답변 (1개)
You iterate over two nested loops, but only the final value of the internal loop is saved (which is always five). Thus you end up with a vector of fives. Also there are a total of 125 calls of the assignment operation, not 25 as you seem to think. If you want only 25 calls then you need to change the steps of your loop variables, something like this:
C = zeros(1,25);
for m = 0:5:20
for n = 1:5
C(:,m+n) = n;
end
end
You do not tell us why you need nested loops, so perhaps one of these might help you, the first uses no loops at all:
B = 1+mod(0:24,5)
the second uses one loop:
A = zeros(1,25);
for k = 1:25
A(:,k) = 1+mod(k-1,5);
end
Also note that I preallocated the output variable before the loops, to prevent it from inefficiently increasing in size within the loop.
댓글 수: 2
Muneer Afzal
2016년 1월 6일
Walter Roberson
2016년 1월 6일
reshape(vector1(:) * vector2(:).', [], 1)
카테고리
도움말 센터 및 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!