How to make a loop run multiple times for different values of a variable.
조회 수: 1 (최근 30일)
이전 댓글 표시
Thanks for taking the time to read this. This is the script I'm working on:
resultX0 = cell(10, 1);
resultY0 = cell(10, 1);
resultG = cell(10, 1);
for i = 1:10
for j = 1:length(q)
[G, X0, Y0] = matrix_plantsubm(M, N, c, n, p, q(j));
resultX0{i} = X0;
resultY0{i} = Y0;
resultG{i} = G;
end
end
I would like this script to run for 10 values of q and return the answers, so I can plug them into the next function. Specifically I would like to have 10 different values of q from 0 to 1. Each result is saved in cell ResultX0 or ResultY0. After running this I have the same matrices for each cell in results. It seems like the code generates only one matrix and keeps it in 10 different cells.
댓글 수: 6
Stephen23
2017년 10월 30일
편집: Stephen23
2017년 10월 30일
"It seems like the code generates only one matrix and keeps it in 10 different cells."
Your code runs okay (I used q=1:10). Lets check the output variable resultG:
>> cellfun(@isequal,repmat(resultG(:),1,N),repmat(resultG(:)',N,1))
ans =
1 0 0 0 0 0 0 0 0 0
0 1 0 0 0 0 0 0 0 0
0 0 1 0 0 0 0 0 0 0
0 0 0 1 0 0 0 0 0 0
0 0 0 0 1 0 0 0 0 0
0 0 0 0 0 1 0 0 0 0
0 0 0 0 0 0 1 0 0 0
0 0 0 0 0 0 0 1 0 0
0 0 0 0 0 0 0 0 1 0
0 0 0 0 0 0 0 0 0 1
>>
Which clearly shows that all G output matrices are different, and are not the same, as you claim.
However X0 and Y0 these will always be the same, as that is how you defined them to be: on every loop iteration the variables M, N, c, and n have exactly the same values, therefore your definitions of X0 and Y0 will always return the same matrices.
It is not clear what you expect to happen, but your code is doing exactly what you tell it to do.
답변 (0개)
참고 항목
카테고리
Help Center 및 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!