Parallel two for loops

1 view (last 30 days)
Muneer Afzal
Muneer Afzal on 6 Jan 2016
Commented: Walter Roberson on 6 Jan 2016
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

Answers (1)

Stephen23
Stephen23 on 6 Jan 2016
Edited: Stephen23 on 6 Jan 2016
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 Comments
Muneer Afzal
Muneer Afzal on 6 Jan 2016
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..
Walter Roberson
Walter Roberson on 6 Jan 2016
reshape(vector1(:) * vector2(:).', [], 1)

Sign in to comment.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!