Storing a Variable from a While Loop

조회 수: 16 (최근 30일)
Billy Dipre
Billy Dipre 2020년 10월 16일
답변: Walter Roberson 2020년 10월 16일
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.

답변 (1개)

Walter Roberson
Walter Roberson 2020년 10월 16일
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

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by