New Lab Manual PSLP
New Lab Manual PSLP
Lab Manual
INSTITUTE VISION
To develop a leaning environment for academic excellence with technological and management
competence at par with international standards and to nurture young minds with high spiritual and
ethical values.
INSTITUTE MISSION
The Institute will focus to incorporate following agendas in the teaching methodology:
COURSE OBJECTIVE
COURSE OUTCOMES
C.252.2 Analyze joint distributions and visualize data using statistical tools.
(Unit II)
correlation methods for analyzing data and making predictions. (Unit III)
5. CO2
Compute covariance and correlation for two datasets
6. CO2
Write a program to visualize statistical data using histogram.
7. CO3
Fitting of regression lines
8. CO3
Perform a Chi-square test for goodness of fit for a given dataset
9. CO3
Perform t-test for comparing means of two samples.
10. Program for forming first simplex table for a three variable linear CO4
programming problem.
11. CO4
Program for solving Transportation Problem of three variables.
12. CO4
Program for solving Assignment Problem of three variables.
EVALUATION SCHEME
Laboratory
Components Internal External
Marks 40 60
Total Marks 100
GUIDELINES FOR CONTINUOUS ASSESSMENT FOR EACH EXPERIMENT
The Rubrics for Experiment execution, Lab file and viva voice is given below:
Accuracy of results.
Results with moderate
Demonstrates excellent
Result accuracy. Demonstrates partial
LAC 2 2 understanding of the
Validation understanding of the concepts
concepts relevant to the
relevant to the program.
program.
One mark for attendance.
Timely
Submission
LAC 4 2 On time submission Late submission
of Lab
Records
CONTENTS
Experiment 1(a): Matrix Addition ........................... ………....7
Experiment 1(b): Matrix Multiplication.................................. 9
Experiment 1(c): Matrix Transpose ...................................... 11
Experiment 2: Fitting Binomial distribution for given N and P…..13
Experiment 3: Fitting Poisson distribution By computing mean….16
Experiment 4: Plotting Standard Normal distribution Curve…..19
Experiment 5: Compute Covariance and Correlation for 2 datasets…..23
Experiment 6: Visualize Statistical Data Using Histogram ... 25
Experiment 7: Fitting Regression Lines ................................ 27
Experiment 8: Perform a chi-square test for goodness to fit for a given data….31
Experiment 9: Perform t-test for comparing means of two samples….34
Experiment 10: Solving a LPP using Simplex Method ......... 38
Experiment 11: Solving Transportation Problem .................. 44
Experiment 12: Solving a 3 by 3Assignment Problem .......... 59
EXPERIMENT 1(A): MATRIX ADDITION
[7]
forj=1:n
B(i,j)=input('\');
end
end
fori=1:m
forj=1:n
C(i,j)=A(i,j)+B(i,j);
end
end
disp('The first matrix is')
disp(A)
disp('The Second matrix is')
disp(B)
disp('The sum of the two matrices is')
disp(C)
[8]
EXPERIMENT 1(B): MATRIX MULTIPLICATION
[9]
ifn==p
disp('Matrices are conformable for multiplication')
else
disp('Matrices are not conformable for multiplication')
break;
end
disp('enter the first Matrix')
fori=1:m
forj=1:n
A(i,j)=input('\');
end
end
disp('enter the second Matrix')
fori=1:p
forj=1:q
B(i,j)=input('\');
end
end
C=zeros(m,q);
fori=1:m
forj=1:q
fork=1:n
C(i,j)=C(i,j)+A(i,k)*B(k,j);
end
end
end
disp('The first matrix is')
disp(A)
disp('The Second matrix is')
disp(B)
disp('The product of the two matrices is')
disp(C)
[10]
EXPERIMENT 1(C): MATRIX TRANSPOSE
[12]
EXPERIMENT 2: FITTING BINOMIAL DISTRIBUTION FOR GIVEN N AND P
Aim/Objective: Program for fitting Binomial distribution when n and p are given
Course Outcome: CO1
Software Used: SCILAB
Theory: A series of independent trials which result in one of the two mutually exclusive
outcomes ‘success’ or ‘failure’ such that the probability of the success (or failure) in each
trials is constant, then such repeated independent trials are called as ‘Bernoulli trials’. A
discrete random variable which results in only one of the two possible outcomes (success or
failure) is called Binomial variable.
Let there be 𝑛 independent finite trials in an experiment such that
i. Each trial has only two possible outcomes success and failure
ii. Probability of success (𝑝) and probability of failure (𝑞) are constant for all the trials
and 𝑝 + 𝑞 = 1.
Then if a random variable 𝑋 denotes the number of successes in 𝑛 trials, then
𝑛
𝑃 (𝑋 = 𝑟 ) = 𝐶𝑟 𝑝𝑟 𝑞 𝑛−𝑟 or 𝑃(𝑟) = 𝑛
𝐶𝑟 𝑞 𝑛−𝑟 𝑝𝑟
∴ Binomial distribution may be given as (𝑞 + 𝑝)𝑟
Sample Problem: Fit a binomial distribution to the following data and compare theoretical
frequencies with actual ones
𝑥 0 1 2 3 4 5 6 7 8 9
𝑓 6 20 28 12 8 6 0 0 0 0
∑ 𝑓𝑥
Solution: Mean of the given distribution = ∑𝑓
, ∑ 𝑓 = 80
0 + 20 + 56 + 36 + 32 + 30 + 0 87
= = = 2.175
80 40
Let mean of binomial distribution to be fitted = 𝑛𝑝 = 2.175
Also 𝑛 = 10 ∴ 𝑝 = 0.2175 𝑞 = 1 − 0.2175 = 0.7825
∴ B.D. is given by 80(0.7825 + 0.2175 )10
Theoretical frequencies using binomial distribution are given in the table below:
𝑥 P(r) = 𝑛 𝐶𝑟 𝑞 𝑛−𝑟 𝑝𝑟 Theoretical frequencies (𝑓) = 80× 𝑃(𝑟)
10 (
0 𝐶0 0.7825)10 (0.2175)0 = 0.086 6.9 = 7(say)
10 (
1 𝐶1 0.7825)9 (0.2175)1 =0.239 19.1 = 19(say)
10 )8 ( )2
2 𝐶2 (0.7825 0.2175 = 0.299 23.9 = 24(say)
10
3 𝐶3 (0.7825)7 (0.2175)3 = 0.22 17.8 = 18(say)
10 )6 ( )4
4 𝐶4 (0.7825 0.2175 = 0.11 8.6 = 9(say)
10
5 𝐶5 (0.7825)5 (0.2175)5 = 0.04 2.9 = 3(say)
[13]
10
6 𝐶6 (0.7825)4 (0.2175)6 = 0.008 0.66 = 0(say)
10
7 𝐶7 (0.7825)3 (0.2175)7 = 0.001 0.11 = 0(say)
10
8 𝐶8 (0.7825)2 (0.2175)8 = 0 0
10 (
9 𝐶9 0.7825)1 (0.2175)9 = 0 0
[14]
[15]
EXPERIMENT 3: FITTING POISSON DISTRIBUTION BY COMPUTING MEAN
CODE:
clc
clear
disp("enter no of observation")
n=input('\')
disp("enter the vlaue of x")
for i=1:n
X(1,i)=input('\')
end
disp("enter no of frequency")
for j=1:n
F(1,j)=input('\')
end
disp("Mean of the distribution is")
M=sum(F.*X)/sum(F)
disp(M)
for i=1:n
P(1,i)=sum(F)*exp(-M)*M^(X(i))/factorial(X(i))
end
disp("Expected frequencies are")
disp(P)
plot2d(X,P)
[17]
[18]
EXPERIMENT 4: PLOTTING STANDARD NORMAL DISTRIBUTION CURVE
[19]
(𝑖𝑖) 𝑃(96 < 𝑋 < 105)
= 𝑃(96 < 100 + 5𝑧 < 105)
96 − 100 105 − 100
= 𝑃( <𝑧< )
5 5
= 𝑃(−0.8 < 𝑧 < 1)
= 𝑃(0 < 𝑧 < 0.8) + 𝑃(0 < 𝑧 < 1)
= 0.2881 + 0.3413 = 0.6294 using Z table
(𝑖𝑖𝑖) 𝑃(𝑋 > 110)
= 𝑃(100 + 5𝑧 > 110)
110 − 100
= 𝑃 (𝑧 > )
5
= 𝑃 (𝑧 > 2)
= 0.5 − 𝑃(0 < 𝑧 < 2)
= 0.5 − 0.4772 = 0.0228 using Z table
(𝑖𝑣) 𝑃 (𝑋 < 92)
= 𝑃(100 + 5𝑧 < 92)
92 − 100
= 𝑃 (𝑧 < )
5
= 𝑃(𝑧 < −1.6)
= 𝑃(𝑧 > 1.6) (Symmetry)
= 0.5 − 𝑃(0 < 𝑧 < 1.6)
= 0.5 − 0.4452 = 0.0548 using Z table
Algorithm:
1. Input:
[20]
Use the sample mean 𝝁 and sample standard deviation 𝝈 to fit a normal distribution.
CODE:
// Clear workspace
clear;
clc;
[21]
[22]
EXPERIMENT 5: COMPUTE COVARIANCE AND CORRELATION FOR 2 DATASETS
Sample Problem: If 𝐶𝑜𝑣 (𝑥, 𝑦) = 10, 𝑣𝑎𝑟(𝑥 ) = 25, 𝑣𝑎𝑟(𝑦) = 9 find coefficient of
correlation.
𝐶𝑜𝑣 (𝑥,𝑦) 10 10
Solution: 𝑟 = = = 5×3 = 0.67
√𝑉𝑎𝑟(𝑥) √𝑉𝑎𝑟(𝑦) √25 √ 9
Algorithm:
1. Input two datasets as vectors.
2. Compute the mean of each dataset.
3. Calculate the covariance using the formula:
Cov(X, Y) = sum((X - mean(X)) .* (Y - mean(Y))) / (n - 1)
4. Compute the correlation using the formula:
Corr(X, Y) = Cov(X, Y) / (std(X) * std(Y))
5. Display the results.
Code:
// Define the datasets
[23]
X=[1,2,3,4,5];// Example dataset 1
Y=[2,4,6,8,10];// Example dataset 2
disp(correlation);
[24]
EXPERIMENT 6: VISUALIZE STATISTICAL DATA USING HISTOGRAM
Algorithm:
1. Input the dataset to be visualized.
2. Define the number of bins for the histogram.
3. Use the histplot function to generate and display the histogram.
4. Customize the plot with labels and title for better visualization.
Code:
// Define the dataset
data=[5,7,8,9,6,7,9,8,10,7,6,8,9,5,6,7,8,9,10,7];
title("Histogram of Dataset");
xlabel("Data Values");
ylabel("Frequency");
[25]
[26]
EXPERIMENT 7: FITTING REGRESSION LINES
[29]
[30]
EXPERIMENT 8: PERFORM A CHI-SQUARE TEST FOR GOODNESS TO FIT FOR A GIVEN DATA
Aim/Objective: Program to test goodness of fit for a given dataset using Chi-square test
Course Outcome: CO3
Software Used: SCILAB
Theory: Chi-square (𝜒 2 ) is a right tailed test and describes the magnitude of discrepancy
between theory and observation. If 𝜒 2 = 0; the observed and expected frequencies
completely coincide, ∴ 𝜒 2 provides a measure of correspondence between theory and
observations. It is one of the simplest and most general tests and can be used to perform
1. test of significance of sample variance
2. test of goodness of fit
3. test of independence of attributes in a contingency table
Chi-Square (𝝌𝟐 ) Test for Testing Goodness of Fit
If 𝑂𝑖 (𝑖 = 1,2, … , 𝑛) be a set of observed (experimental) frequencies and 𝐸𝑖 (𝑖 = 1,2, … , 𝑛) be
the corresponding set of expected (theoretical) frequencies,
(𝑂𝑖 −𝐸𝑖 )2
then 𝜒 2 = ∑𝑛𝑖=1 ; with degrees of freedom (𝜈) = 𝑛 − 1.
𝐸𝑖
There are some underlying conditions for applying 𝜒 2 test such as:
1. Sum of frequencies should be large (at least 50)
2. No theoretical cell-frequencies should be small, if small (less than 5) theoretical
frequencies occur, regrouping of two or more cells must be done before
calculating (𝑂𝑖 − 𝐸𝑖 ). Degree of freedom is determined by the number of classes after
regrouping.
Sample Problem: Apply 𝜒 2 test of goodness to fit for the following data:
Observed frequency: 1 5 20 28 42 22 15 5 2
Theoretical Frequency: 1 6 18 25 40 25 18 6 1
Value of 𝜒 2 for 6, 7, 8 degrees of freedom at 5% significance level are 12.592, 14.067 and
15.507 respectively.
Solution: Since first two and the last two cells frequencies are smaller than prescribed,
regrouping the data to 7 cells:
𝑂𝑖 6 20 28 42 22 15 7
𝐸𝑖 : 7 18 25 40 25 18 7
Degrees of freedom (𝜈) = 7 − 1 = 6
(𝑂𝑖 −𝐸𝑖 )2
𝜒 2 = ∑𝑛𝑖=1 𝐸𝑖
(6−7)2 (20−18)2 (15−18)2 (7−7)2
= + + ⋯+ + = 1.685
7 18 18 7
Table value of 𝜒 2 for 6 degrees of freedom at 5% level = 12.592
Calculated value of 𝜒 2 is much less than table value ∴ the fit is very good.
[31]
Algorithm:
3. Compare the calculated value of 𝜒 2 with the critical value from the chi-square table for
the given degree of freedom and significance level α.
4. Decision:
5. Output:
CODE:
// Degrees of freedom
n=length(observed);
df=n-1;
// Significance level
alpha=0.05;
[32]
// Output results
disp("Chi-Square Statistic: "+string(chi_square_stat));
disp("Degrees of Freedom: "+string(df));
disp("Critical Value: "+string(chi_square_critical));
// Decision
ifchi_square_stat>chi_square_criticalthen
disp("Reject the null hypothesis (H0): The data does not fit the expected distribution.");
else
disp("Fail to reject the null hypothesis (H0): The data fits the expected distribution.");
end
[33]
EXPERIMENT 9: PERFORM T-TEST FOR COMPARING MEANS OF TWO SAMPLES
and compare with table value of 𝑡 (say 𝑡1 ) at (𝑛1 + 𝑛2 − 2) degrees of freedom. Hypothesis
is accepted if calculated value of |𝑡| < 𝑡1 .
Sample Problem: Two independent samples showing weights in ounces of eight and seven
items are given below:
Sample I: 10 12 13 11 15 9 12 14
Sample II: 9 11 10 13 9 8 10
Is the difference between the means of the samples significant?
Value of 𝑡 at 5% level of significance for 15 degrees of freedom is 2.16.
[34]
Solution: Let the null hypothesis (𝐻0 ) be: 𝜇1 ≈ 𝜇2
Here 𝑛1 = 8 and 𝑛2 = 7, calculating sample means and standard deviations
𝑥 (𝑥 − 𝑥) (𝑥 − 𝑥)2 𝑦 (𝑦 − 𝑦) (𝑦 − 𝑦)2
10 -2 4 9 -1 1
12 0 0 11 1 1
13 1 1 10 0 0
11 -1 1 13 3 9
15 3 9 9 -1 1
9 -3 9 8 -2 4
12 0 0 10 0 0
14 2 4
∑ 𝑥 = 96 ∑ 𝑦 = 70
96 28 70 16
𝑥= = 12 𝑦= = 10
8 7
∑(𝑥−𝑥)2+∑(𝑦−𝑦)2 ∑(𝑥−12)2+∑(𝑦−10)2 28+16
𝑠=√ =√ √8+7−2 = 1.8
𝑛1+𝑛2 −2 8+7−2
𝑥−𝑦 12−10
∴𝑡= 1 1
= 1 1
= 2.15
𝑠√ + (1.8)√ +
𝑛1 𝑛2 8 7
Use the t-distribution table or calculate the p-value for the given degree of freedom
and significance level (e.g., 𝛼 = 0.05)
[35]
If the absolute value of the T-statistic exceeds the critical value (or p-value is less
than 𝛼), reject the null hypothesis.
CODE:
[36]
[37]
EXPERIMENT 10: SOLVING A LPP USING SIMPLEX METHOD
𝑠1 0 4 1 1 1 0 4
𝑠2 0 2 1 -1 0 1 2→
Z=0 -3 -2 0 0 ∆𝑗 = 𝐶𝐵 𝑥𝑗 − 𝐶𝑗
𝑥1 enters and 𝑠2 leaves
𝑠1 0 2 0 2 1 -1 →
𝑥1 3 2 1 -1 0 1
Z=6 0 -5 0 3 ∆𝑗 = 𝐶𝐵 𝑥𝑗 − 𝐶𝑗
𝑥2 enters and 𝑠1 leaves
[38]
𝑥2 21 0 1 1 1
−
2 2
𝑥1 33 1 0 1 1
2 2
Z = 11 5 1 ∆𝑗 ≥ 0
0 0 22
∴ Maximum Z = 11 at 𝑥1 = 3 and 𝑥2 = 1
Algorithm to Display First Simplex Table of a Linear Programing Problem
Enter the number of variables in the objective function and the number of constraints
Using loops enter all the coefficients of the objective function and constraint
equations
Make the choices for minimization or maximization by entering 1 or 2
Make the choices for ≤ or ≥ signs by entering 1 or 2
For each ≤ signs make a column for slack variable
Print the first simplex table using all the given values
CODE:
clc
clear
p=input("Enter number of varibles in the objective function :");
q=input("Enter number of constraint equations :");
disp('Enter coefficients of the objective function :')
for i=1:p
A(i)=input('\');
end
m=input("Enter 1 to minimize or 2 to maximize");
disp('Enter constraint equations :')
for i=1:q
disp('enter ' + string(i)+ ' equation: ')
for j=1:p
disp('enter coefficient ' + string(j)+ ' :')
B(i,j)=input('\');
if(j==p) then
printf("\n whether you want to maximize or minimize this equation:\nEnter \n 1. for<= \n 2.
for >= :")
C(i)=input('\');
printf("enter constant");
D(i)=input('\');
[39]
end
end
end
printf("%dx%d + ",B(i,j),j);
if(j==p) then
if(C(i)==1) then
printf(" <= %d",D(i));
else if(C(i)) then
printf(" >= %d",D(i));
end
end
end
end
printf("\n");
end
printf("\n\n====================SIMPLEX TABLE
IS=======================\n\n\n");
printf(" CJ |");
for i=1:p-1
printf(" %d",A(i));
end
for i=1:q-1
[40]
printf(" 0s%d",i);
end
printf("\n---------------------------------------------------------");
printf("\nBVCbXb |");
for i=1:p
printf(" x%d",i);
end
for i=1:q
printf(" s%d",i);
end
printf(" Min Xb/x");
printf("\n---------------------------------------------------------\n");
for i=1:p
printf("s%d 0 %d | ",i,D(i));
for j=1:q
printf("%d ",B(i,j));
end
for j=1:q
if(j==i) then
printf("1 ");
else
printf("0 ");
end
end
printf("\n");
end
printf("--------------------------------------------------------");
printf("\n ZJ-CJ |");
for i=1:p
printf(" -%d",A(i));
end
for i=1:q
printf(" 0");
end
[41]
[42]
[43]
EXPERIMENT 11: SOLVING TRANSPORTATION PROBLEM
𝑥𝑖𝑗 ≥ 0∀i, j
Also for a balanced transportation
problem∑𝑚 𝑛
𝑖=1 𝑎𝑖 = ∑𝑗=1 𝑏𝑗
w1 w2 w3 w4 ai↓
S1 19 30 50 10 7
S2 70 30 40 60 9
S3 40 8 70 20 18
bj 5 8 7 14
Solution: (i) Northwest Corner ruleGiven transportation problem is already
balanced, ∴ allocating min [5,7] =5 to cell (1,1) and adjusting supply and demand across the
row and column.
[44]
w1 w2 w3 w4 ai↓
S1 19 5 30 50 10 7,2
S2 70× 30 40 60 9
S3 40× 8 70 20 18
bj 5 8 7 14
Moving to right hand cell (1,2), allocating min [2,8] =2 and adjusting supply and demand
across the row and column.
w1 w2 w3 w4 ai↓
S1 19 5 30 2 50× 10× 7,2
S2 70× 30 40 60 9
S3 40× 8 70 20 18
bj 5 8,6 7 14
Moving down to cell (2,2), allocating min [6,9] =6 and adjusting supply and demand across
the row & column.
w1 w2 w3 w4 ai↓
S1 19 5 30 2 50× 10× 7,2
S2 70 × 30 6 40 60 9,3
S3 40× 8× 70 20 18
bj 5 8,6 7 14
Moving to right hand cell (2,3), allocating min [3,7] =3and adjusting supply & demand
across the row and column.
w1 w2 w3 w4 ai↓
S1 19 5 30 2 50× 10× 7,2
S2 70 × 30 6 40 3 60× 9,3
S3 40× 8× 70 20 18
bj 5 8,6 7,4 14
Moving down to cell (3,3), allocating min [4,18] =4 and adjusting supply and demand
across the row & column.
w1 w2 w3 w4 ai↓
S1 19 5 30 2 50× 10× 7,2
S2 70 × 30 6 40 3 60× 9,3
S3 40× 8× 70 4 20 18,14
bj 5 8,6 7,4 14
Allocating the balance supply/demand i.e. ‘14’ in the cell (3,4), the initial basic feasible
solution using north west corner rule is given by
[45]
w1 w2 w3 w4 ai↓
S1 19 5 30 2 50× 10× 7,2
S2 70 × 30 6 40 3 60× 9,3
S3 40× 8× 70 4 20 14 18,14
bj 5 8,6 7, 4 14
w1 w2 w3 w4 ai↓
S1 19 30 × 50 10 7 (9) (9)
S2 70 30 × 40 60 9 (10) (20)
S3 40× 8 8 70× 20 10 18 , 10 (12) (20)×
bj 5 8 7 14, 4
(21) (22) (10) (10)
(21) ×(10) (10)
Again adjusting corresponding supply and demand
w1 w2 w3 w4 ai↓
S1 19 5 30 × 50 10 7,2 (9) (9) (9)
S2 70 × 30 × 40 60 9 (10) (20) (20)
S3 40× 88 70× 20 10 18 , 10 (12) (20) ×
bj 5 8 7 14 , 4
(21) (22) (10) (10)
(21) × (10) (10)
(51) (10) (50)
Rewriting the difference of minimum cost and next minimum cost, skipping allocated cells
and crossed out cells, maximum penalty is 50 against W4.Allocating min[2,4]=2 to minimum
cost cell (1,4) in S1 , also adjusting corresponding supply and demand
w1 w2 w3 w4 ai↓
S1 19 5 30 × 50 10 2 7,2 (9) (9) (9) (40)
[46]
S2 70 × 30 × 40 60 9 (10) (20) (20) (20)
S3 40× 88 70× 20 10 18 , 10 (12) (20) ×
bj 5 8 7 14 , 4, 2
(21) (22) (10) (10)
(21) × (10) (10)
(51) (10) (50)
(10) (50) (50)
Adding and subtracting min[2,8]=2 at vertices of the loop to adjust supply and demand
requirements as given below
?+2 2-2
8-2 10+2
Modified distribution of allocations is as shown in the table below:
w1 w2 w3 w4
S1 19 5 30 50 10 𝟐
S2 70 30 2 40 7 60
S3 40 8𝟔 70 20 𝟏𝟐
New transportation cost = 19(5) + 10(2) + 30(2)+ 40(7) + 8(6)+20(12) = 743units
To check whether the new solution is optimal, assign set of numbers u i and vj, putting u1 =0
arbitrarily as all the rows are having equal number of allocations. Calculating remaining ui
and vjusing the relation cij = (ui + vj)for occupied cells.
w1 w2 w3 w4
S1 19 ∗ 10 ∗ u1 =0
S2 30 ∗ 40 ∗ u2 =32
S3 8 ∗ 20 ∗ u3=10
v1=19 v2=-2 v3=8 v4=10
Now entering cijfor each unoccupied cell (i,j)in the upper left corner and (ui + vj) for the
same cell in the upper right corner.
w1 w2 w3 w4
S1 ∗ 30 -2 50 8 ∗ u1 = 0
+32 +42
S2 70 41 ∗ ∗ 60 42 u2=32
+29 +18
S3 40 29 ∗ 70 18 ∗ u3=10
+11 +52
v1=19 v2=-2 v3=8v4=10
[48]
All dij> 0, ∴ the solution is optimal and minimum transportation cost = 743 units
I. Finding an initial basic feasible solution using North West Corner Rule:
1. Balance the transportation problem if not originally by adding a dummy source or
destination making ∑𝑚 𝑛
𝑖=1 𝑎𝑖 = ∑𝑗=1 𝑏𝑗 ,with zero transportation cost in added cells.
2. Start with the cell in the upper left hand corner which is north west corner (1,1)
and allocate the maximum possible amount 𝑥𝑖𝑗 = Min (𝑎𝑖 , 𝑏𝑗 ) in the cell (i, j),
such that either the availability of the source 𝑆𝑖 is exhausted or the requirement at
destination 𝐷𝑗 is satisfied or both.
3. Adjust supply and demand across the row and column in which allocation 𝑥𝑖𝑗 has
been made.
4. Move to right hand cell (1,2) if there is still any available quantity left otherwise
move down to cell (2,1).
5. Continue the procedure until all the available quantity is exhausted.
[49]
CODE:
clc
prices = [1, 2, 3;
8, 5, 4;
3, 1, 6]
demand = [100, 30, 70]
supply = [110, 40, 50]
prices = evstr(x_matrix('setprices', prices));
demand = evstr(x_matrix('setdemand', demand));
supply = evstr(x_matrix('submit offer', supply));
LEFT = 1
RIGHT = 2
UP = 3
DOWN = 4
// The function of calculating the cost of the transferred plan
function res=cost(prices, plan)
cntCols = length(prices(1,:))
cntRows = length(prices(:,1))
res = 0
for i=1:cntRows
for j=1:cntCols
res = res + prices(i,j) * plan(i,j)
end
end
endfunction
// a function that looks for available angles in a given direction
// and returns them in descending order of proximity to the edge
function [corners, success]=getAvailableCorner(basis, direction, initialPoint, i, j)
success = 0
corners = []
currentCorner = 1
cntCols = length(basis(1,:))
cntRows = length(basis(:,1))
colModificator = 0;
[50]
rowModificator = 0;
if direction == LEFT then
colModificator = -1
end
if direction == RIGHT then
colModificator = 1
end
if direction == UP then
rowModificator = -1
end
if direction == DOWN then
rowModificator = 1
end
i = i + rowModificator
j = j + colModificator
while i ~= 0 && j ~= 0 &&i<= cntRows&& j <= cntCols
if basis(i,j) ~= 0 || [i, j] == initialPoint then
corners(currentCorner,:) = [i,j]
currentCorner = currentCorner + 1
success = 1
end
i = i + rowModificator
j = j + colModificator
end
if success == 1 then
cornersReverse = []
for iter = 1:length(corners(:,1))
cornersReverse(iter,:) = corners(length(corners(:,1)) - iter + 1, :)
end
corners = cornersReverse
end
endfunction
// recursive looping function
[51]
function [nodes, success]=buildCycle(basis, initialPoint, currentPoint, direction)
success = 0
nodes = []
possibleDirections = []
if initialPoint == currentPoint then
possibleDirections = [LEFT, RIGHT, UP, DOWN]
else if direction == LEFT || direction == RIGHT then
possibleDirections = [UP, DOWN]
else if direction == UP || direction == DOWN then
possibleDirections = [LEFT, RIGHT]
end; end; end
for directionIdx = 1:length(possibleDirections)
[corners, suc] = getAvailableCorner(basis, possibleDirections(directionIdx), initialPoint,
currentPoint(1), currentPoint(2))
if suc == 1 then
possibleToCloseCycle = 0
successWithCorners = 0
for cornIdx = 1:length(corners(:,1))
if (corners(cornIdx,:) == initialPoint) then
possibleToCloseCycle = 1
continue
end
[subNodes, suc] = buildCycle(basis, initialPoint, corners(cornIdx,:),
possibleDirections(directionIdx))
if suc == 1 then
successWithCorners = 1
nodeIdx = 1
nodes(nodeIdx, :) = currentPoint
for subNodeIdx = 1:length(subNodes(:,1))
nodeIdx = nodeIdx + 1
nodes(nodeIdx, :) = subNodes(subNodeIdx,:)
end
break
end
[52]
end
if successWithCorners == 1 then
success = 1
break
else if possibleToCloseCycle == 1 then
nodes(1, :) = currentPoint
nodes(2, :) = initialPoint
success = 1
break
end; end
end
end
endfunction
cntCols = length(prices(1,:))
cntRows = length(prices(:,1))
plan = [] // reference plan
plan(cntRows, cntCols) = 0 // fill with zeros
// Calculation of the original reference plan using the northwest corner method
tempDemand = demand
tempSupply = supply
for j=1:cntCols// iterate over columns (customers)
for i=1:cntRows// iterate over rows (suppliers)
currentSupply = min(tempDemand(j), tempSupply(i))
plan(i,j) = currentSupply
tempDemand(j) = tempDemand(j) - currentSupply
tempSupply(i) = tempSupply(i) - currentSupply
if tempDemand(j) == 0 then
break
end
end
end
disp("Initial plan:")
disp(plan)
[53]
printf("\nThe cost is %d у.е.\n\n\n", cost(prices, plan))
// Plan optimization
optimal = 0
UNKNOWN_POTENCIAL = 9999999
iteration = 0
while optimal ~= 1
iteration = iteration + 1
potencialU = []
potencialV = []
for i = 1:cntRows
potencialU(i) = UNKNOWN_POTENCIAL // type unknown yet potential
end
for i = 1:cntCols
potencialV(i) = UNKNOWN_POTENCIAL
end
potencialU(1) = 0
continuePotentialing = 1
// calculation of potentials by points in the route
while continuePotentialing == 1
continuePotentialing = 0
// we continue to calculate the potentials if
// for one of the values ​​of the plan, both potentials are unknown
for j=1:cntCols// iterate over columns (customers)
for i=1:cntRows// iterate over rows (suppliers)
if (plan(i,j) == 0) then
continue
end
if potencialU(i) == UNKNOWN_POTENCIAL &&potencialV(j) ==
UNKNOWN_POTENCIAL then
continuePotentialing = 1
continue
end
if potencialU(i) == UNKNOWN_POTENCIAL then
potencialU(i) = prices(i,j) - potencialV(j)
[54]
end
if potencialV(j) == UNKNOWN_POTENCIAL then
potencialV(j) = prices(i,j) - potencialU(i)
end
end
end
end
// Calculating estimates for non-basic variables
notBasis = [] // reference plan
notBasis(cntRows, cntCols) = 0 // fill with zeros
optimal = 1
maxI = 0;
maxJ = 0;
maxNB = 0;
for j=1:cntCols// iterate over columns (customers)
for i=1:cntRows// iterate over rows (suppliers)
if (plan(i,j) ~= 0) then
continue
end
notBasis(i,j) = potencialU(i) + potencialV(j) - prices(i,j)
if notBasis(i,j) > 0 then
optimal = 0
if maxNB<notBasis(i,j) then
maxNB = notBasis(i,j)
maxI = i
maxJ = j
end
end
end
end
if optimal == 1 then
printf("Iteration %d. The current plan is optimal!", iteration)
break
else
[55]
printf("Iteration %d. Current plan is not optimal. Plan optimization", iteration)
end
[nodes, success] = buildCycle(plan, [maxI, maxJ], [maxI, maxJ], "")
if success == 0 then
disp("Loop building error. Shutdown")
break
end
// Among the even nodes of the cycle (those who will have a negative 0) looking for the
minimum value
minNode = 99999999
for node = 2:2:length(nodes(:,1))
if minNode>plan(nodes(node, 1), nodes(node, 2)) then
minNode = plan(nodes(node, 1), nodes(node, 2))
end
end
for node = 2:length(nodes(:,1))
nodeI = nodes(node, 1)
nodeJ = nodes(node, 2)
if modulo(node, 2) == 0 then
plan(nodeI, nodeJ) = plan(nodeI, nodeJ) - minNode// for even subtract min. meaning
else
plan(nodeI, nodeJ) = plan(nodeI, nodeJ) + minNode// for odd ones add min. meaning
end
end
disp("New plan:")
disp(plan)
printf("\nThe cost is %d у.е.\n\n\n", cost(prices, plan))
end
tableStr = 2;
table = []
table(1,:) = [" " "From supplier" "To the consumer" "Quantity"];
for i = 1:cntRows
for j = 1:cntCols
[56]
if plan(i,j) ~= 0 then
str = []
str(1) = " "
str(2:4) = string([i, j, plan(i,j)])
table(tableStr,:) = str
tableStr = tableStr + 1
end
end
end
disp(table)
f = createWindow();
f.figure_size = [400 400];
f.figure_name = "Final answer";
as = f.axes_size;
ut = uicontrol("style", "table",..
"string", table,..
"position", [0 -50 400 400],..
"tag", "Final answer");
matrix(ut.string, size(table))
Output:
[57]
[58]
EXPERIMENT 12: SOLVING A 3 BY 3ASSIGNMENT PROBLEM
Such that
∑𝑛𝑗=1 𝑥𝑖𝑗 = 1 for i = 1,….,n
∑𝑛𝑖=1 𝑥𝑖𝑗 = 1for j = 1,….,n
𝑥𝑖𝑗 = 1if ith person is assigned with jth job, 0 otherwise
Algorithm for solving a 3 by 3 assignment problem (Single step assignments)
1. Prepare a square 3 × 3 matrix. If not, make it square by adding suitable number of
dummy rows (or columns) with zero cost elements.
2. Subtract the minimum element of each row from every element of that row.
3. Further modify the resulting matrix by subtracting the minimum element of each
column from all the elements of the respective columns, so that each row and column
is having a zero element.
4. Now start making assignments row - wise. Examine each row one by one and assign a
‘1’’ to ‘0’ in the rows having single zeros. Then, mark a ‘×’ to all zeroes in the
column in which assignment has been made so that no other assignment can be made
in the same column
5. Repeat the procedure for the columns.
6. Stop if all 3assignments have been made.
[59]
Sample problem: A department head has four subordinates and four tasks have to be
performed. Time (hours) each man would take to perform each task is given below. How
the tasks should be allocated to each subordinate so as to minimize the total man-hours?
Subordinates
S1 S2 S3 S4
Tasks T1 5 6 8 9
T2 6 8 10 6
T3 9 5 8 5
T4 9 8 7 10
Solution: Given assignment problem is balanced i.e. number of rows and columns are equal.
Subtracting minimum element in each row from all the elements of the row, hence inducing a
zero element in each row
S1 S2 S3 S4
T1 0 1 3 4
T2 0 2 4 0
T3 4 0 3 0
T4 2 1 0 3
Each column is having a zero element, so matrix is unchanged by subtracting minimum
element in each column. Now making assignments on zeros to rows having single zeros and
crossing out remaining zeros in same columns and repeating the process with columns if any
allocations are left in row assignments
S1 S2 S3 S4
T1 0 1 3 4
T2 2 4 0
T3 4 0 3
T4 2 1 0 3
All the assignments have been made in single step.
Optimal assignments: T1 - S1 , T2 - S4 , T3 - S2 , T4 - S3
Minimum man hours = (5+6+5+7) hours = 23 hours
[60]
CODE:
clc
clear
n=input("how many workers and job do you have :");
printf("\nenter time of\n\n");
for i=1:n
for j=1:n
printf("worker %d job%d :",i,j);
T(i,j)=input('\');
end
end
printf("\nDATA YOU ENTERED IS :\n ");
for i=1:n
printf("job%d ",i);
end
for i=1:n
printf("\nworker%d ",i);
for j=1:n
printf("%d ",T(i,j));
end
end
minim=[1000,1000,1000,1000,1000,1000,1000,1000,1000];
for i=1:n
for j=1:n
if(T(i,j)<=minim(i)) then
minim(i)=T(i,j);
end
end
end
printf("\n");
for i=1:n
for j=1:n
T(i,j)=T(i,j)-minim(i);
end
[61]
end
printf("\n");
printf("\n\n*************data after row minimum decrement is***************\n\t\t");
for i=1:n
printf("job%d ",i);
end
for i=1:n
printf("\nworker%d ",i);
for j=1:n
printf("%d ",T(i,j));
end
end
zerr=[1000,1000,1000,1000,1000,1000];
zerc=[1000,1000,1000,1000,1000,1000];
for i=1:n
for j=1:n
if(T(i,j)==0) then
zerr(i)=0;
zerc(j)=0;
end
end
end
f=0;
y=0;
for i=1:n
if(zerr(i)) then
f=1;
end
end
for i=1:n
if(zerc(i)) then
y=1;
end
end
if((f==1)||(y==1)) then
[62]
mn=[1000,1000,1000,1000,1000,1000,1000,1000,1000];
for j=1:n
for i=1:n
if(T(i,j)<=mn(j)) then
mn(j)=T(i,j);
end
end
end
for j=1:n
for i=1:n
T(i,j)=T(i,j)-mn(j);
end
end
printf("\n\n*************data after column minimum decrement is***************\n");
for i=1:n
printf("job%d ",i);
end
for i=1:n
printf("\nworker%d ",i);
for j=1:n
printf("%d ",T(i,j));
end
end
end
printf("\n\n\n************Final job assignment is**************");
for i=1:n
for j=1:n
if(T(i,j)==0) then
printf("\n assign job %d to worker %d",j,i);
for z=1:n
if (z==i) then
continue;
end
if(T(z,j)==0) then
[63]
T(z,j)=1000;
end
for l=1:n
if(l==j) then
continue;
end
if(T(i,l)==0) then
T(i,l)=1000;
end
end
end
end
end
end
printf(“\n");
[64]
[65]