Calculating Factorials
In Matlab
Main Concept
In mathematics, the factorial of a nonnegative
integer n (denoted by n!), is the product of all the
positive integers less than or equal to n.
By definition, the value of 0! is 1.
Example:
5! = 1 · 2 · 3 · 4 · 5 = 120
Three easy ways to do it in Matlab:
1.- With for-loops (not recommended)
2.- Without for-loops (much better)
3.- Built-in function (the obvious way)
1.- With a for-loop
% Enter the factorial you want to calculate (assume n > 0)
n = 5
% Initialize your product
f1 = 1;
% You can go from 1 to your desired value in steps of 1
for i = 1 : n
% Just multiply all the integers in the interval
f1 = f1 * i;
end
% Here’s your result
f1
2.- Without a for-loop
% Enter the factorial you want to calculate
n = 5
% You can use the built-in function prod to multiply all the
% elements in a vector. Hint: choose your elements wisely!
f2 = prod( [1 : n] )
3.- Built-in function
% You can also use the built-in function factorial,
% that happens to be made for this purpose!
n = 5
f3 = factorial( n )
For more examples and details, visit:
matrixlab-examples.com/factorials.html

Code Factorials in Matlab

  • 1.
  • 2.
    Main Concept In mathematics,the factorial of a nonnegative integer n (denoted by n!), is the product of all the positive integers less than or equal to n. By definition, the value of 0! is 1. Example: 5! = 1 · 2 · 3 · 4 · 5 = 120
  • 3.
    Three easy waysto do it in Matlab: 1.- With for-loops (not recommended) 2.- Without for-loops (much better) 3.- Built-in function (the obvious way)
  • 4.
    1.- With afor-loop % Enter the factorial you want to calculate (assume n > 0) n = 5 % Initialize your product f1 = 1; % You can go from 1 to your desired value in steps of 1 for i = 1 : n % Just multiply all the integers in the interval f1 = f1 * i; end % Here’s your result f1
  • 5.
    2.- Without afor-loop % Enter the factorial you want to calculate n = 5 % You can use the built-in function prod to multiply all the % elements in a vector. Hint: choose your elements wisely! f2 = prod( [1 : n] )
  • 6.
    3.- Built-in function %You can also use the built-in function factorial, % that happens to be made for this purpose! n = 5 f3 = factorial( n )
  • 7.
    For more examplesand details, visit: matrixlab-examples.com/factorials.html