Combine for loop output??

6 views (last 30 days)
Jonathan Good on 4 May 2018
Edited: Wick on 4 May 2018
Hi I'm writing some code for my homework that will allow the user to choose a number of lines they want to buy in a lottery. My code is generating the numbers in the desired range, it is outputting the numbers from a for loop for the specified number of times, ultimately i want the combined output to go into a table to display all of the results. The purpose of the exercise isn't to be sleek its to use a variety of functions in one piece of code. Here's what i have so far:
% I am producing a code that will allow the
% user to choose a desired number of lines required for a euromillions
% lottery draw (Max 7 per slip)
User select number of lines they would like
number_of_lines = menu('Hello there welcome to the lottery draw please select a number of lines you wish to purchase? Remember its £2.50 a line and 7 lines maximum per ticket', '1','2','3','4','5','6','7');
% function to generate number of lines selected
% row vectors containing limits for numbers
main_draw_numbers = (1:50)
lucky_stars = (1:12)
% preallocate the output array
main_draw = zeros(number_of_lines,5);
% preallocate the output array
stars_draw = zeros(number_of_lines,2);
for draw=1:number_of_lines
% increment counter
main_draw = sort(datasample(main_draw_numbers,5,'Replace',false));
stars_draw = sort(datasample(lucky_stars,2,'Replace',false));
full_draw = [main_draw stars_draw];
T = array2table(full_draw,...
'VariableNames',{'Ball_1','Ball_2','Ball_3','Ball_4','Ball_5','Lucky_star_1','Lucky_star_2'})
end
Wick on 4 May 2018
I see you edited the code so it combines the full and stars draws in the FOR loop. But if you don't cat the loops together you're still going to get a single line in your table.
Something like
full_draw = [];
for ...
full_draw = [full_draw; main_draw stars_draw];
end

Wick on 4 May 2018
Edited: Wick on 4 May 2018
If you're not trying to be pretty or efficient you can do the following:
for draw=1:number_of_lines
% increment counter
main_draw = datasample(main_draw_numbers,5,'Replace',false);
stars_draw = datasample(lucky_stars,2,'Replace',false);
if draw == 1
T = array2table([main_draw stars_draw],...
'VariableNames',{'ball1','ball2','ball3','ball4','ball5','Lucky1','Lucky2'});
else
T = [T; array2table([main_draw stars_draw],...
'VariableNames',{'ball1','ball2','ball3','ball4','ball5','Lucky1','Lucky2'})];
end
end
"Proper" MATLAB would be to pre-allocate the memory for table T. But this works for a small 'for' loop like this.
Rather than initialize, I jsut made an IF statement decide to start the table or cat to it.