In: Mechanical Engineering
The factorial of an integer ? is defined using the following equation: ?! = ? ∗ (? − 1) ∗ (? − 2) ∗ … ∗ 2 ∗ 1 In combinatorics, permutations is the number of ways of selecting a subset of some elements such that the order matters. For example, there are 6 permutations of letters A, B, and C. A B C ,A C B, B A C, B C A, C A B, C B A, The permutation of selecting ? elements from a set of ? elements can be calculated using the following equation: ?(?, ?) = ?! (? − ?)! On the other hand, combinations is the number of ways of selecting a subset of some elements such that the order does not matter. The combination of selecting elements from a set of m elements can be calculated using the following equation: ?(?, ?) = ( ? ? ) = ?! ?! (? − ?)! Instructions Add a section / cell in your MATLAB m-file script for problem 3 that: • Prompts the user to enter integer ? between 2 and 12 (inclusive) o If the input is invalid, displays an error message and prompt the user to try again, as many times as necessary (use a loop to accomplish this instead of terminating the program) • Prompts the user to enter integer ? between 2 and ? (inclusive) o If the input is invalid, displays an error message and prompt the user to try again, as many times as necessary (use a loop to accomplish this instead of terminating the program) • Determines and displays the following: o ?! o ?(?, ?) o ?(?, ?) This program must use loops to calculate the results – DO NOT use any pre-defined MATLAB functions related to factorials, permutations, and/or combinations.
MATLAB script is given below-
clear
clc
%loop to get the value of n from user
while (1)
n=input('Enter the integer between 2 and 12 (inclusive): ');
if n>2 && n<=12
break
end
end
%loop to get the value of k from user
while (1)
fprintf('Enter the integer between 2 and %d (inclusive)',n)
k=input(': ');
if k>2 && k<=n
break
end
end
% to calculate the factorial of n!
fact_n=1;
for i=1:n
fact_n=i*fact_n;
end
% to calculate the factorial of k!
fact_k=1;
for i=1:k
fact_k=i*fact_k;
end
% to calculate the factorial of (n-k)!
fact_n_k=1;
for j=1:(n-k)
fact_n_k=fact_n_k*j;
end
% to caculate the values of P(n,k) and C(n,k)
P_n_k=fact_n*fact_n_k; C_n_k=fact_n*fact_n_k*fact_k;
% to print the values on command window
fprintf('The value of P(n,k)=%d, C(n,k)=%d and
n!=%d\n\n\n',P_n_k,C_n_k,fact_n)
-----------------------------------------------------------------------------------------------------------------------------------
Output-
Enter the integer between 2 and 12 (inclusive): 7
Enter the integer between 2 and 7 (inclusive): 4
The value of P(n,k)=30240, C(n,k)=725760 and n!=5040