Storing a Variable from a While Loop

12 visualizaciones (últimos 30 días)
Billy Dipre
Billy Dipre el 16 de Oct. de 2020
Respondida: Walter Roberson el 16 de Oct. de 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.

Respuestas (1)

Walter Roberson
Walter Roberson el 16 de Oct. de 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

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by