% Jake Bobowski % July 27, 2017 % Created using MATLAB R2014a % This tutorial will introduce simple implementations of while loops % in MATLAB. clearvars % Here's while loop that calculates the factorial of n. Start with n = 4 % to make sure things are working properly. The loop executes until n > 1. % That is, the the last iteration of the loop will occur when n = 2. (You % could actually let the while loop run until n = 1 since factorial*1 = % factorial). n = 4; disp(['n = ' num2str(n)]) factorial = 1; while n > 1 factorial = factorial*n; n = n-1; end disp(['n! = ' num2str(factorial)]) % Here's a more interesting factorial n = 150; disp(['n = ' num2str(n)]) factorial = 1; while n > 1 factorial = factorial*n; n = n-1; end disp(['n! = ' num2str(factorial)]) % Maybe you want to the user to be able to enter only integer numbers. See % the nested control structure tutorial to see an implementation of this % check. That tutorial will also show you how to calculate the factorials % of a bunch of n values and then plot the results vs n.
n = 4 n! = 24 n = 150 n! = 5.713383956445858e+262