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일

0 개 추천

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
Muneer Afzal 2016년 1월 6일
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 2016년 1월 6일
reshape(vector1(:) * vector2(:).', [], 1)

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

질문:

2016년 1월 6일

댓글:

2016년 1월 6일

Community Treasure Hunt

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

Start Hunting!

Translated by