While-loop

The second repeating construct in MATLAB is the while-loop. With the for-loop you have to specify beforehand how many times you want to execute the loop. With the while-loop this number of executions is not specified beforehand, but rather depends on whether or not a certain expression is true or false. The general form of a while-loop is:
while logical expressions
    command lines
end
Example 6.6: A `fair' lottery. Here we use the while-loop. Write a script m-file with the name `lottery.m' and the following contents:
% let MATLAB determine a random value between 1 and 10
n = round(rand(1)*10+0.5);
% initialisation of stopping variable
stop = 0;
while stop == 0
    choice = input('Enter an integer between 1 and 10')
    if choice == n
        stop = 1;
        disp('*** ***')
        disp('You have won!!!!')
        disp('*** ***')
    else
        disp('Sorry, incorrect: next player please')
    end
end



Previous      Next      Up      Contents


Esteur 2010-03-22