Can I store each iteration of this WHILE loop as a new variable (preferably without resorting to eval() )

6 views (last 30 days)
I'm practicing coding by creating an interactive cross country analysis program that would allow someone to enter times from as many races as desired and run regressions on the data.
I accomplished this for a preset number of races but ran into trouble when trying to generalize the program to be able to run for n-sets of races. I had hoped to accomplish this by creating a loop that would begin entering data for a new 'average_time' variable each time 'yes' was selected from a menu.
I've heard that this could be done using the eval() function but that this method is usually discouraged, so I'd like some advice on the best method.
The pertinent part of the script I'm using is
minutes_1=input('Input race one minutes ');
seconds_1 = input('Input race one seconds ');
average_time_1=(sum(minutes_1).*60+sum(seconds_1))/7/60;
more_data=menu('Would you like to enter another race''s data?', 'yes','no');
if more_data ~=0
while more_data==1
% This part of the code is supposed to repeat the above
% process for as long as someone keeps entering 'yes' into the
% 'Would you like to enter another race''s data?' menu and creating a new average time variable for each iteration of the loop.
minutes_n=input('Input next race''s minutes ');
seconds_n = input('Input next race''s seconds ');
average_time_n=(sum(minutes_n).*60+sum(seconds_n))/7/60;
more_data=menu('Would you like to enter another race''s data?', 'yes','no');
end
else
% I would like this section to display all of the average times
% generated in minutes:seconds. I can do this for a specific average
% time using: disp(['The average time is ' num2str(mins_1) ':' num2str(secs_1)])
% Is there a way to write this as a general statement that will display average time 1 through average time n in this format?
end
Any other advice on cleaning this up would also be appreciated
  1 Comment
dpb
dpb on 28 Aug 2014
Several choices -- simplest in idea is to use a cell array of the 1D vectors. Each race is a new cell so the number of races entered is size(cell_array).
You then process the cell array via cellfun for all or any selected subset to get the averages and/or other statistics desired.
Many other data structures could be developed that would hold the data as well, of course.

Sign in to comment.

Accepted Answer

José-Luis
José-Luis on 28 Aug 2014
Edited: José-Luis on 28 Aug 2014
counter = 1;
your_array = cell(some_reasonable_size,1);
while something
do_stuff;
your_array(counter) = {something};
counter = counter + 1;
end

More Answers (0)

Community Treasure Hunt

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

Start Hunting!