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
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.
POLLY
POLLY 2017-10-30
编辑:POLLY 2017-10-30
@Stephen I want to generate 10 different matrices for X0,Y0 and G0. Each of them depends on q=0:0.1:1(10 ways). Each matrix is supposed to be saved in individual cell.

请先登录,再进行评论。

回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by