Storing a Variable from a While Loop

41 views (last 30 days)
Billy Dipre
Billy Dipre on 16 Oct 2020
Answered: Walter Roberson on 16 Oct 2020
I am trying to assign a variable an array that changes each iteration of a while loop. I want each array to be stored however. My code is
N = 10; %The starting number of randomly generated integers
while N <= 200 %200 is the maximum number of randomly generated integers that I want
x = randi(2^52,N,1); % its 2^52 because I want it to be any number generated
N = N + 10; %each time the number of random integers increases by 10
end
I don't know where to go from here. But I want each new array assigned to x stored somewhere.

Answers (1)

Walter Roberson
Walter Roberson on 16 Oct 2020
all_x = cell(20, 1);
N = 10; %The starting number of randomly generated integers
counter = 0;
while N <= 200 %200 is the maximum number of randomly generated integers that I want
x = randi(2^52,N,1); % its 2^52 because I want it to be any number generated
counter = counter + 1;
all_x{counter} = x;
N = N + 10; %each time the number of random integers increases by 10
end
Or better:
all_x = cell(20, 1);
for counter = 1 : 20
N = 10*counter;
x = randi(2^52, N, 1);
all_x{counter} = x;
end
It is necessary to use a cell array here because each time you are generating a different number of points.
An alternative would be to initialize a 200 x 20 array of NaN, and fill in only the part that is appropriate:
all_x = nan(200,20);
for counter = 1 : 20;
N = counter * 10;
x = randi(2^52, N, 1);
all_x(1:N, counter) = x;
end

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!