Parallel two for loops
Mostrar comentarios más antiguos
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
Respuestas (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 comentarios
Muneer Afzal
el 6 de En. de 2016
Walter Roberson
el 6 de En. de 2016
reshape(vector1(:) * vector2(:).', [], 1)
Categorías
Más información sobre Loops and Conditional Statements en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!