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 个)

Stephen23
Stephen23 2016-1-6
编辑:Stephen23 2016-1-6
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 个评论

Actually I am generating a vector by multiple of two matrices of size 23 the resultant is required to be saved of 529 values in different columns in 1st row. Therefore it is required to solve that enigma..
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!

Translated by