This algorithm creates a guessing program in MATLAB. First, it randomly picks an integer in range 1 to 10. Then, the user should guess the number as soon as possible. A counter keeps track of number of guesses made.
% This is a guessing game counter=0; real_number=rand(1); real_number=10*real_number; number=ceil(real_number); fprintf('I am thinking a number between 1 and 10.\n'); guess=input('Guess a number: '); while guess~= number counter = counter + 1; if guess>number fprintf('Your guess is too high!\n'); guess=input('Guess another number: '); else fprintf('Your guess is too low!\n'); guess=input('Guess another number: '); end end counter= counter + 1; fprintf('Congratulations! You guessed the correct number in %g shots. \n', counter); |

I know this post is old, but I randomly stumbled upon it while googling some Matlab stuff (I just started learning it). Here’s a quick rewrite of your guessing game to make it more concise:
counter = 0;
number = ceil(10*rand(1));
fprintf(‘I am thinking a number between 1 and 10.\n’);
while (guess = input(‘Guess a number: ‘)) ~= number
counter += 1;
if guess > number
fprintf(‘Your guess is too high!\n’);
else
fprintf(‘Your guess is too low!\n’);
end
end
fprintf(‘Congratulations! You guessed the correct number in %g shots. \n’, counter+1);