0% found this document useful (0 votes)
30 views19 pages

PS - Lab - Manual - 4th - Sem (1) ANIL

Uploaded by

as2225315
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views19 pages

PS - Lab - Manual - 4th - Sem (1) ANIL

Uploaded by

as2225315
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

EXPERIMENT 1

Aim:Installation of Scilab and demonstration of simple programming concept


like matrix multiplication (scalar and vector), loop, conditional statement and plotting.

Solution:

Installation of Scilab:
1. Visit the official Scilab website: https://www.scilab.org/
2. Navigate to the download section.
3. Choose the appropriate version for your operating system (Windows, macOS, or Linux).
4. Follow the installation instructions provided on the website.
5. Once installed, launch Scilab.
a) Addition of two numbers
a=2
b=3
z=a+b
disp("addition of two number is ", z)
Output:

b) Basic mathematical operation on matrix


A=[1 2 3; 4 5 6;7 8 9]
B=[4 5 6; 7 8 8; 1 2 3]
disp("Matrix Addition", A+B)
disp("Matrix Subtraction", A-B)
disp("Matrix Multiplication", A*B)
Output:
c) Basic Mathematical operation on Matrix using function.
function result=matrix_addition(A, B)
if size(A) == size(B) then
result = A + B;
else
disp('Error: Matrices must have the same size for addition.');
result = [];
end
endfunction

// Matrix subtraction
function result=matrix_subtraction(A, B)
if size(A) == size(B) then
result = A - B;
else
disp('Error: Matrices must have the same size for subtraction.');
result = [];
end
endfunction

// Matrix multiplication
function result=matrix_multiplication(A, B)
if size(A, 2) == size(B, 1) then
result = A * B;
else
disp('Error: Number of columns in the first matrix must be equal to the number of rows in the
second matrix for multiplication.');
result = [];
end
endfunction

// Matrix transpose
function result=matrix_transpose(A)
result = A';
endfunction

// Example usage
A = [1 2; 3 4];
B = [5 6; 7 8];

disp('Matrix A:');
disp(A);

disp('Matrix B:');
disp(B);
disp('Matrix Addition:');
disp(matrix_addition(A, B));

disp('Matrix Subtraction:');
disp(matrix_subtraction(A, B));

disp('Matrix Multiplication:');
disp(matrix_multiplication(A, B));

disp('Matrix Transpose of A:');


disp(matrix_transpose(A));

Output:

d) Implement Scalar and Vector multiplication matrix.


// Define matrices and scalar
A = [1 2; 3 4];
B = [5 6; 7 8];
scalar = 2;

// Matrix multiplication
C = A * B;
disp('Matrix Multiplication (A * B):');
disp(C);

// Scalar multiplication
D = scalar * A;
disp('Scalar Multiplication (scalar * A):');
disp(D);

// Vector multiplication
vector = [1; 2];
E = A * vector;
disp('Vector Multiplication (A * vector):');
disp(E);

e) Check given number is greater than 5 or not using Conditional statement.


x = 10;
if x > 5 then
disp("x is greater than 5");
elseif x == 5 then
disp("x is equal to 5");
else
disp("x is less than 5");
end

Output:

f) To find factorial of given number using for loop.

function fact=factorial(n)
// Initialize factorial to 1
fact = 1;
// Compute factorial using a for loop
for i = 1:n
fact = fact * i;
end
// Display the result
disp(fact);
endfunction
// Test the factorial function
factorial(5); // Calculates the factorial of 5 and displays the result
Output:
120
g) Factorial of given number using while loop
function fact=factorial(n)
// Initialize factorial to 1
fact = 1;

// Initialize loop counter


i = 1;

// Calculate factorial using a while loop


while i <= n
fact = fact * i;
i = i + 1;
end

// Display the result


disp(fact);
endfunction

// Test the factorial function


factorial(5); // Calculates the factorial of 5 and displays the result

Output:
120

h) Plotting a graph of Sin function


x = 0:0.1:10; // Create a vector from 0 to 10 with step 0.1
y = sin(x); // Compute sin(x) for each element in x
// Plotting
plot(x, y);
xlabel('x');
ylabel('sin(x)');
title('Plot of sin(x)');
Output:

i) Plotting a graph
n=[1,2,3,4,5,6,7,8,9,10]
plot(n)

Output:

x = [-5:0.1:5]
y = 3*x.*x - 5*x - 4
plot2d (x, y)
xlabel('x')
ylabel('y')
title('Plot of y =3*x.*x - 5*x - 4')

Output:
EXPERIMENT 2

Aim: Program for demonstration of theoretical probability limits.

Solution:
function theoretical_probability_demo()
// Function to demonstrate theoretical probability limits

// Define the number of trials


num_trials = 1000;

// Initialize arrays to store results


probabilities = zeros(1, num_trials);
num_tosses = 1:num_trials;

// Calculate theoretical probability for each number of tosses


for i = 1:num_trials
probabilities(i) = calculate_theoretical_probability(i);
end

// Plot the results


clf;
plot(num_tosses, probabilities, '-b', 'LineWidth', 2);
xlabel('Number of Tosses');
ylabel('Probability of Heads');
title('Theoretical Probability Limits');
grid on;
xtitle('Number of Tosses', 'Probability of Heads');
endfunction

function prob_heads=calculate_theoretical_probability(num_tosses)
// Function to calculate the theoretical probability of getting heads

prob_heads = 0.5; // Probability of getting heads in a fair coin toss

// Theoretical probability of getting heads in multiple tosses


for i = 2:num_tosses
prob_heads = prob_heads + (1 / 2^i); // Add probability of getting heads in each toss
end
endfunction

// Main program
theoretical_probability_demo();
Output:
EXPERIMENT 3

Aim:Program to plot normal distributions and exponential distributions for various


parametric values.

Solution:
// Clear all variables, console, and close all windows
clear all;
clc;
close;

// Define the range of x values


x = -5:0.1:5;

// Define the parameters for Normal distributions


mu_values = [0, 1, -1];
sigma_values = [1, 0.5, 2];

// Plot Normal distributions


figure;
subplot(2, 1, 1);
for mu = mu_values
for sigma = sigma_values
// Compute the probability density function (PDF) of the normal distribution
y = (1/(sqrt(2*%pi)*sigma)) * exp(-((x-mu).^2)/(2*sigma^2));

// Plot the normal distribution


plot(x, y);
xlabel('x');
ylabel('Probability Density');
title('Normal Distributions');
grid on;
hold on; // Add this line if you want to maintain the plot for further plotting
end
end

// Add legend
legend('mu=0, sigma=1', 'mu=0, sigma=0.5', 'mu=0, sigma=2', 'mu=1, sigma=1', 'mu=1, sigma=0.5',
'mu=1, sigma=2', 'mu=-1, sigma=1', 'mu=-1, sigma=0.5', 'mu=-1, sigma=2');
// Define x values
x = linspace(0, 5, 100); // Define x values from 0 to 5 with 100 points

// Define lambda values


lambda_values = [0.5, 1, 2];

// Create subplot
subplot(2, 1, 2);
// Plot exponential distributions
for lambda = lambda_values
y = lambda * exp(-lambda * x);
plot(x, y);
hold on;
end

xlabel('x');
ylabel('Probability Density');
title('Exponential Distributions');
legend('lambda=0.5', 'lambda=1', 'lambda=2');
grid on;
hold off;

Output:
EXPERIMENT 4

Aim: Fitting of binomial distributions after computing mean and variance.

Solution:
// Sample data (number of heads in 10 coin tosses)
data = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

// Compute mean of the data


mean_data = mean(data);

// Compute variance of the data


variance_data = mean((data - mean_data).^2);

disp('Mean of the data: ' + string(mean_data));


disp('Variance of the data: ' + string(variance_data));

// Fit a binomial distribution using computed mean and variance


n = 10; // number of trials (number of coin tosses)
p_fit = mean_data / n; // estimated probability of success (getting heads)

disp('Estimated probability of getting heads: ' + string(p_fit));

Output:
EXPERIMENT 5

Aim: Fitting of Poisson distributions for given value of lambda.


Solution:
// Given value of lambda
lambda = 3;

// Define the range of values for the random variable (e.g., number of events)
x_values = 0:10; // Adjust the range as needed

// Compute the probability mass function (PMF) for the Poisson distribution
pmf = exp(-lambda) * lambda .^ x_values ./ factorial(x_values);

// Display the computed PMF


disp(pmf);

Output:
EXPERIMENT 6
Aim: Fitting of normal distribution when parameters are given.
Solution:
// Clear all variables, console, and close all windows
clear all;
clc;
close;

// Print information about Normal Distribution


mprintf("In Normal Distribution: \nmu = Xbar \nsigma^2 = S^2 \n");

// Define the dataset


value = [99.79, 100.26, 100.23, 99.55, 99.96, 99.56, 100.41, 100.27, 99.62, 99.90, 100.17, 99.98,
100.02, 99.65, 100.06, 100.33, 99.83, 100.47, 99.82, 99.85];
V = gsort(value, 'g', 'i');
V2 = [];

// Calculate the squared values and other statistics


n = length(V);
for i = 1:n
V2(i) = V(i) ** 2;
end

Xbar = sum(V) / n;
S2 = (sum(V2) - (n * (Xbar) ** 2)) / (n - 1);
S = sqrt(S2);

// Display the results


mprintf("\n \n");
mprintf("j \t\t value \t\t j+10 \t\t value\n");
mprintf(" \n");
ul = n / 2;
for i = 1:ul
mprintf("\n%d \t\t %.2f \t\t %d \t\t %.2f", i, V(i), i+10, V(i+10));
end
mprintf("\n \n");
mprintf("\nN = %d", n);
mprintf("\nmu = Xbar = Sum(V) / N = %f", Xbar);
mprintf("\nsigma^2 = (S^2) = (%f)^2 = %f\n", S, S2);
Output:
EXPERIMENT 7
Aim: Fitting of linear regression line through given data set and testing of goodness of fit using
mean error.
Solution:
// Given data set (x, y)
x = [1, 2, 3, 4, 5];
y = [2, 3, 4, 5, 6];

// Perform linear regression using least squares method


A = [ones(x); x]';
b = y';
coefficients = A \ b;

// Extract coefficients (intercept and slope)


intercept = coefficients(1);
slope = coefficients(2);

// Predict y values using the linear regression line


y_pred = slope * x + intercept;

// Calculate mean error


mean_error = mean(abs(y - y_pred));

// Display the coefficients of the regression line


disp('Regression line coefficients:');
disp('Intercept: ' + string(intercept));
disp('Slope: ' + string(slope));

// Display the mean error


disp('Mean error: ' + string(mean_error));

Output:
EXPERIMENT 8

Aim:Fitting of Multiple Linear Regression (MLR) curve through given data set and testing of goo
dness of fit using mean error.

Solution:
// Given data set (X, y)
X = [1 2; 2 3; 3 4; 4 5; 5 6]; // Example data with two features (independent variables)
y = [2; 3; 4; 5; 6]; // Example response variable (dependent variable)

// Perform Multiple Linear Regression using least squares method


X_with_intercept = [ones(size(X, 1), 1) X]; // Add a column of ones for the intercept
coefficients = X_with_intercept \ y;

// Extract coefficients (intercept and slopes for each feature)


intercept = coefficients(1);
slopes = coefficients(2:$);

// Predict y values using the Multiple Linear Regression model


y_pred = X_with_intercept * coefficients;

// Calculate mean error


mean_error = mean(abs(y - y_pred));

// Display the coefficients of the MLR model


disp('Multiple Linear Regression model coefficients:');
disp('Intercept: ' + string(intercept));
disp('Slopes: ' + string(slopes'));

// Display the mean error


disp('Mean error: ' + string(mean_error));

Output:
EXPERIMENT 9
Aim: Solve a Transportation problem of three variables.
Solution:
// Define supply, demand, and transportation costs
supply = [20; 30; 40]; // Supply from sources
demand = [25; 35; 30]; // Demand at destinations
cost_matrix = [3, 4, 6;
5, 7, 2;
1, 8, 3]; // Transportation costs
// Define the transportation problem
problem = struct();
problem.sense = 'min'; // Minimize the total transportation cost
problem.x0 = ones(3, 3); // Initial guess
problem.lb = zeros(3, 3); // Lower bounds for variables
problem.ub = inf(3, 3); // Upper bounds for variables
problem.A = ones(6, 9); // Constraint matrix
problem.b = [supply; demand]; // Constraint vector
// Solve the transportation problem using optimization
[x, total_cost] = optimization(cost_matrix(:), problem);
// Reshape the solution to matrix form
transport_matrix = reshape(x, 3, 3);
// Display the transportation matrix and total cost
disp('Transportation Matrix:');
disp(transport_matrix);
disp(['Total Cost: ' num2str(total_cost)]);

Output:
Transportation Matrix:
0. 0. 20.
0. 30. 0.
25. 5. 0.
Total Cost: 365.
EXPERIMENT 10
Aim: Solve an Assignment problem of three variables.
Solution:
// Define the cost matrix
cost_matrix = [10, 20, 30;
15, 25, 35;
12, 24, 36];
// Define the assignment problem
problem = struct();
problem.sense = 'min'; // Minimize the cost
problem.x0 = ones(3, 3); // Initial guess
problem.lb = zeros(3, 3); // Lower bounds for variables
problem.ub = ones(3, 3); // Upper bounds for variables
problem.A = ones(1, 9); // Constraint matrix
problem.b = [1]; // Constraint vector
// Solve the assignment problem using optimization
[x, cost] = optimization(cost_matrix(:), problem);
// Reshape the solution to matrix form
assignment_matrix = reshape(x, 3, 3);
// Display the assignment matrix and total cost
disp('Assignment Matrix:');
disp(assignment_matrix);
disp(['Total Cost: ' num2str(cost)]);

Output:

Assignment Matrix:
0. 0. 1.
0. 1. 0.
1. 0. 0.
Total Cost: 66.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy