How to make a loop run multiple times for different values of a variable.

7 views (last 30 days)
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 Comments
Stephen23
Stephen23 on 30 Oct 2017
Edited: Stephen23 on 30 Oct 2017
"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 on 30 Oct 2017
Edited: POLLY on 30 Oct 2017
@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.

Sign in to comment.

Answers (0)

Categories

Find more on Creating and Concatenating Matrices 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!