0% found this document useful (0 votes)
4 views67 pages

Matlab Python Programming

The document outlines a skill enhancement course in MATLAB and Python programming for engineering students, detailing course objectives, contents, and outcomes. It includes practical tasks and experiments, structured into units covering MATLAB basics, mathematical operations, and Python programming concepts. Additionally, it provides references for textbooks and online resources to support learning.

Uploaded by

satyasmart321
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)
4 views67 pages

Matlab Python Programming

The document outlines a skill enhancement course in MATLAB and Python programming for engineering students, detailing course objectives, contents, and outcomes. It includes practical tasks and experiments, structured into units covering MATLAB basics, mathematical operations, and Python programming concepts. Additionally, it provides references for textbooks and online resources to support learning.

Uploaded by

satyasmart321
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/ 67

DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING

Name of the student:

Registration No: Section:

Year and Sem:

Branch:

Skill Course Name:

Course Code:

Academic Year:
INDEX
MATLAB PROGRAMMING

S.NO. DATE TASK/EXPERIMENT PAGE NO. MARKS SIGN.

10

11

12

13

14

15

16

17

18

19

20
INDEX
PYTHON PROGRAMMING

S.NO. DATE TASK/EXPERIMENT PAGE NO. MARKS SIGN.

10

11

12

13

14

15

16

17

18

19

20
2304501–MATLAB/PYTHON FOR ENGINEERS
Programme B. Tech &
&Branch ECE Sem Category L T P Credits

Prerequisites Nil 3 Skill Enhancement 0 1 2 2


course

Course Objectives:
1. Understanding the MATLAB software environment.
2. Demonstrate how MATLAB can be used to solve a range of mathematical problems.
3. Introduction about Polynomials, Curve Fitting, and Interpolation concepts.
4. Introduce basic concepts in Python programming language.
5. Introduce different types of decision control and iterative statements in python.
Now a days programming knowledge has become very essential for engineering
Preamble:
professionals as well as scientists and researchers to develop simulation models,
performing analysis, optimization & decision making. MATLAB and Python are
two excellent tools for visualization and manipulation of engineering data as well
as performing various engineering computations.
Course Contents:

Unit-1 Starting with MATLAB

Starting MATLAB, MATLAB Windows, working in the Command Window, Arithmetic


Operations with Scalars, Display Formats, Elementary Math Built-In Functions, Defining Scalar
Variables, Script Files.
Creating Arrays: Creating a 1-D vector array, creating a 2-D matrix array, Array Addressing,
using a colon (:) in addressing arrays, Built-In Functions for handling arrays, Strings and Strings
as Variables.

Unit-2 Mathematical Operations and 2D-Plotting

Addition and Subtraction, Array Multiplication, Array Division, Element-By-Element Operations,


Built-in MATH Functions, Generation of Random Numbers, Examples of MATLAB
Applications.
Two-Dimensional Plots: The Plot Command, the fplot Command, Plotting Multiple Graphs in
the Same Plot, Plotting Multiple Graphs in the Same Plot, formatting a Plot, Plots with Logarithmic
Axes, Plots with Error Bars, Plots with Special Graphics, Histograms, Polar Plots, Putting Multiple
Plots on the Same Page, Multiple Figure Windows, Examples of MATLAB Applications.
Unit-3 Polynomials, Curve Fitting, and Interpolation

Value of a Polynomial, Roots of a Polynomial, Addition, Multiplication, and Division of


Polynomials, Derivatives of Polynomials, Curve Fitting, Interpolation, The Basic Fitting Interface,
Examples of MATLAB Applications, Introduction to Simulink.

Unit-4 Basics of Python Programming

Introduction, Features of Python, History of Python, Applications of Python, Literal constants:


Numbers & Strings, Variables and Identifiers, Data Types, Input operation, Comments, Reserved
Keywords, Indentation, Operators and Expressions: Arithmetic, Comparison, Assignment, Unary,
Bitwise, Shift, Logical, Membership & Identity, Operations on strings: Concatenation,
Multiplication & Slice a string, other data Types: Tuples, Lists & Dictionary, Type Conversion. A
few example Programs using Python.

Unit-5 Decision Control Statements in Python

Introduction, conditional branching statements: if, if-else, Nested if, if-elif-else statements, Basic
Loop statements: while, for, Nested Loops, break, continue, pass, else with Loops Statements. A
few example Programs using Python.

Total Hours: 45

Text Books:

1 MATLAB: An Introduction with Applications – Amos Gilat, Wiley Publishers, Fourth


Edition.

2 Python Programming: Using Problem Solving Approach, R Thareja, Oxford University


Press, 2017.

Reference Books:

1 Essential MATLAB for Engineers and Scientists – Brian H. Hahan and Daniel T. Valentine,
Elsevier Publications, Fourth Edition.

2 Python Programming, S Sridhar, J Indumathi, V M Hariharan, 2nd Edition, Pearson, 2024

Web References:

1 https://www.tutorialspoint.com/matlab/matlab_overview.htm

2 https://www.coursera.org/learn/python-for-applied-data-science-ai
COURSE OUTCOMES: BT Mapped
Upon completion of the course, students shall have ability to (Highest Level)

CO 1 Understand MATLAB basic concepts. L2

Understand various arithmetic operations on arrays and 2D L2


CO 2
Plotting in MATLAB.

Understand Relationships among two or more data points using L3


CO 3
curve fitting and interpolation in MATLAB.

Understand Python syntax, deftly utilizing basic programming L2


CO 4
concepts.

Apply conditional branching and loop statements to write basic L3


CO 5
programs in python.
MATLAB® Basic Functions Reference
MATLAB Environment Defining and Changing Array Variables
clc Clear command window a = 5 Define variable a with value 5
help fun Display in-line help for fun A = [1 2 3; 4 5 6] Define A as a 2x3 matrix
doc fun A = [1 2 3 “space” separates columns
Open documentation for fun
4 5 6] “;” or new line separates rows
load("filename","vars") Load variables from .mat file
[A,B] Concatenate arrays horizontally
uiimport("filename") Open interactive import tool
[A;B] Concatenate arrays vertically
save("filename","vars") Save variables to file
x(4) = 7 Change 4th element of x to 7
clear item Remove items from workspace
A(1,3) = 5 Change A(1,3) to 5
examplescript Run the script file named
x(5:10) Get 5th to 10th elements of x
examplescript
format style x(1:2:end) Get every 2nd element of x (1st to last)
Set output display format
ver x(x>6) List elements greater than 6
Get list of installed toolboxes
x(x==10)=1 Change elements using condition
tic, toc Start and stop timer
A(4,:) Get 4th row of A
Ctrl+C Abort the current calculation
A(:,3) Get 3rd column of A
Operators and Special Characters A(6, 2:5) Get 2nd to 5th element in 6th row of A

+, -, *, / A(:,[1 7])=A(:,[7 1]) Swap the 1st and 7th column


Matrix math operations
.*, ./ a:b [a, a+1, a+2, …, a+n] with a+n≤b
Array multiplication and division
(element-wise operations) a:ds:b Create regularly spaced vector with
^, .^ Matrix and array power spacing ds

\ linspace(a,b,n) Create vector of n equally spaced values


Left division or linear optimization
.', ' logspace(a,b,n) Create vector of n logarithmically spaced
Normal and complex conjugate
transpose values

==, ~=, <, >, <=, >= zeros(m,n) Create m x n matrix of zeros
Relational operators
ones(m,n) Create m x n matrix of ones
&&, ||, ~, xor Logical operations
(AND, OR, NOT, XOR) eye(n) Create a n x n identity matrix
; Suppress output display A=diag(x) Create diagonal matrix from vector
... Connect lines (with break) x=diag(A) Get diagonal elements of matrix
% Description Comment meshgrid(x,y) Create 2D and 3D grids
'Hello' Definition of a character vector rand(m,n), randi Create uniformly distributed random
"This is a string" numbers or integers
Definition of a string
randn(m,n) Create normally distributed random
str1 + str2 Append strings
numbers

Special Variables and Constants Complex Numbers


ans Most recent answer i, j, 1i, 1j Imaginary unit
pi π=3.141592654… real(z) Real part of complex number
i, j, 1i, 1j Imaginary unit imag(z) Imaginary part of complex number
NaN, nan Not a number (i.e., division by zero) angle(z) Phase angle in radians
Inf, inf Infinity conj(z) Element-wise complex conjugate
eps Floating-point relative accuracy isreal(z) Determine whether array is real

mathworks.com/help/matlab
Elementary Functions Plotting
sin(x), asin Sine and inverse (argument in radians) plot(x,y,LineSpec) Plot y vs. x
Line styles: (LineSpec is optional)
sind(x), asind Sine and inverse (argument in degrees)
-, --, :, -. LineSpec is a combination of
sinh(x), asinh Hyperbolic sine and inverse (arg. in Markers: linestyle, marker, and
radians) +, o, *, ., x, s, d color as a string.
Analogous for the other trigonometric functions: Colors: Example: "-r"
cos, tan, csc, sec, and cot r, g, b, c, m, y, k, w = red solid line without markers
abs(x) Absolute value of x, complex magnitude title("Title") Add plot title
exp(x) Exponential of x legend("1st", "2nd") Add legend to axes
sqrt(x), nthroot(x,n) Square root, real nth root of real numbers x/y/zlabel("label") Add x/y/z axis label
log(x) Natural logarithm of x x/y/zticks(ticksvec) Get or set x/y/z axis ticks
log2(x), log10 Logarithm with base 2 and 10, respectively x/y/zticklabels(labels) Get or set x/y/z axis tick labels
factorial(n) Factorial of n x/y/ztickangle(angle) Rotate x/y/z axis tick labels
sign(x) Sign of x x/y/zlim Get or set x/y/z axis range
mod(x,d) Remainder after division (modulo) axis(lim), axis style Set axis limits and style
ceil(x), fix, floor Round toward +inf, 0, -inf text(x,y,"txt") Add text
round(x) Round to nearest decimal or integer grid on/off Show axis grid
hold on/off Retain the current plot when
adding new plots
Tables subplot(m,n,p), Create axes in tiled positions
table(var1,...,varN) Create table from data in variables tiledlayout(m,n)
var1, ..., varN yyaxis left/right Create second y-axis
readtable("file") Create table from file figure Create figure window
array2table(A) Convert numeric array to table gcf, gca Get current figure, get current axis
T.var Extract data from variable var clf Clear current figure
T(rows,columns), Create a new table with specified close all Close open figures
T(rows,["col1","coln"]) rows and columns from T
T.varname=data Assign data to (new) column in T Common Plot Types
T.Properties Access properties of T
categorical(A) Create a categorical array
summary(T), groupsummary Print summary of table
join(T1, T2) Join tables with common variables

Tasks (Live Editor)


Live Editor tasks are apps that can be added to a live script to interactively
perform a specific set of operations. Tasks represent a series of MATLAB
commands. To see the commands that the task runs, show the generated
code.

Common tasks available from the Live Editor tab on the


desktop toolstrip:
• Clean Missing Data • Clean Outlier
• Find Change Points • Find Local Extrema
Plot Gallery: mathworks.com/products/matlab/plot-gallery
• Remove Trends • Smooth Data

mathworks.com/help/matlab
Programming Methods Numerical Methods
Functions fzero(fun,x0) Root of nonlinear function
% Save your function in a function file or at the end fminsearch(fun,x0) Find minimum of function
% of a script file. Function files must have the
fminbnd(fun,x1,x2) Find minimum of fun in [x1, x2]
% same name as the 1st function
function cavg = cumavg(x) %multiple args. possible fft(x), ifft(x) Fast Fourier transform and its inverse
cavg=cumsum(vec)./(1:length(vec));
end
Integration and Differentiation
Anonymous Functions
% defined via function handles integral(f,a,b) Numerical integration
fun = @(x) cos(x.^2)./abs(3*x); (analogous functions for 2D and 3D)
trapz(x,y) Trapezoidal numerical integration

Control Structures diff(X) Differences and approximate derivatives


gradient(X) Numerical gradient
if, elseif Conditions
curl(X,Y,Z,U,V,W) Curl and angular velocity
if n<10
disp("n smaller 10") divergence(X,..,W) Compute divergence of
elseif n<=20 vector field
disp("n between 10 and 20") ode45(ode,tspan,y0) Solve system of nonstiff ODEs
else
disp("n larger than 20") ode15s(ode,tspan,y0) Solve system of stiff ODEs

Switch Case deval(sol,x) Evaluate solution of differential equation


n = input("Enter an integer: "); pdepe(m,pde,ic,... Solve 1D partial differential equation
switch n bc,xm,ts)
case -1 pdeval(m,xmesh,... Interpolate numeric PDE solution
disp("negative one") usol,xq)
case {0,1,2,3} % check four cases together
disp("integer between 0 and 3")
otherwise Interpolation and Polynomials
disp("integer value outside interval [-1,3]")
end % control structures terminate with end interp1(x,v,xq) 1D interpolation
(analogous for 2D and 3D)
For-Loop
pchip(x,v,xq) Piecewise cubic Hermite polynomial
% loop a specific number of times, and keep
interpolation
% track of each iteration with an incrementing
% index variable spline(x,v,xq) Cubic spline data interpolation
for i = 1:3 ppval(pp,xq) Evaluate piecewise polynomial
disp("cool");
mkpp(breaks,coeffs) Make piecewise polynomial
end % control structures terminate with end
unmkpp(pp) Extract piecewise polynomial details
While-Loop
poly(x) Polynomial with specified roots x
% loops as long as a condition remains true
n = 1; polyeig(A0,A1,...,Ap) Eigenvalues for polynomial eigenvalue
nFactorial = 1; problem
while nFactorial < 1e100 polyfit(x,y,d) Polynomial curve fitting
n = n + 1;
nFactorial = nFactorial * n; residue(b,a) Partial fraction expansion/decomposition
end % control structures terminate with end roots(p) Polynomial roots
polyval(p,x) Evaluate poly p at points x
Further programming/control commands
break polyint(p,k) Polynomial integration
Terminate execution of for- or while-loop
continue polyder(p) Polynomial differentiation
Pass control to the next iteration of a loop
try, catch Execute statements and catch errors

mathworks.com/help/matlab
Matrices and Arrays Descriptive Statistics
length(A) Length of largest array dimension sum(A), prod Sum or product (along columns)
size(A) Array dimensions max(A), min, bounds Largest and smallest element
numel(A) Number of elements in array mean(A), median, mode Statistical operations
sort(A) Sort array elements std(A), var Standard deviation and variance
sortrows(A) Sort rows of array or table movsum(A,n), movprod, Moving statistical functions
movmax, movmin, n = length of moving window
flip(A) Flip order of elements in array
movmean, movmedian,
squeeze(A) Remove dimensions of length 1 movstd, movvar
reshape(A,sz) Reshape array cumsum(A), cumprod, Cumulative statistical functions
repmat(A,n) cummax, cummin
Repeat copies of array
smoothdata(A) Smooth noisy data
any(A), all Check if any/all elements are nonzero
nnz(A) histcounts(X) Calculate histogram bin counts
Number of nonzero array elements
find(A) corrcoef(A), cov Correlation coefficients, covariance
Indices and values of nonzero elements
xcorr(x,y), xcov Cross-correlation, cross-covariance
normalize(A) Normalize data
Linear Algebra
detrend(x) Remove polynomial trend
rank(A) Rank of matrix
isoutlier(A) Find outliers in data
trace(A) Sum of diagonal elements of matrix
det(A) Determinant of matrix
poly(A) Characteristic polynomial of matrix
Symbolic Math*
eig(A), eigs sym x, syms x y z Declare symbolic variable
Eigenvalues and vectors of matrix (subset)
inv(A), pinv eqn = y == 2*a + b Define a symbolic equation
Inverse and pseudo inverse of matrix
norm(x) Norm of vector or matrix solve(eqns,vars) Solve symbolic expression
for variable
expm(A), logm) Matrix exponential and logarithm
subs(expr,var,val) Substitute variable in expression
cross(A,B) Cross product
expand(expr) Expand symbolic expression
dot(A,B) Dot product
factor(expr) Factorize symbolic expression
kron(A,B) Kronecker tensor product
simplify(expr) Simplify symbolic expression
null(A) Null space of matrix
assume(var,assumption) Make assumption for variable
orth(A) Orthonormal basis for matrix range
assumptions(z) Show assumptions for
tril(A), triu Lower and upper triangular part of matrix
symbolic object
linsolve(A,B) Solve linear system of the form AX=B fplot(expr), fcontour, Plotting functions for
lsqminnorm(A,B) Least-squares solution to linear equation fsurf, fmesh, fimplicit symbolic expressions
qr(A), lu, chol Matrix decompositions diff(expr,var,n) Differentiate symbolic expression
svd(A) Singular value decomposition dsolve(deqn,cond) Solve differential
gsvd(A,B) Generalized SVD equation symbolically

rref(A) int(expr,var,[a, b]) Integrate symbolic expression


Reduced row echelon form of matrix
taylor(fun,var,z0) Taylor expansion of function

*requires Symbolic Math Toolbox

mathworks.com/help/matlab

© 2024 The MathWorks, Inc. MATLAB and Simulink are registered trademarks of The MathWorks, Inc. See mathworks.com/trademarks for a list of additional trademarks.
Other product or brand names may be trademarks or registered trademarks of their respective holders.
APPARATUS REQUIRED:
HARDWAR: Personal Computer
SOFTWARE: MATLAB online
PROCEDURE:
1. Login to MathWorks account
2. Click on MATLAB
3. Click on Open MATLAB online
4. Click on New Script
5. Type the program in editor window
6. Save the script file in current directory
7. Run the program
8. If any error occurs in the program, then correct the errors and run it again.
9. Observe the output in command window\ Figure window.
1. The following problems can be solved by writing commands in the Command Window, or
by writing a program in a script file and then executing the file.

22+5.12 √412−5.22 7𝜋 7𝜋
a) b) c)cos ( ) + tan ( ) sin (150 )
50−6.32 𝑒5−100.53 9 15

Script file:

clc;
clear all;
disp('Part (a)')
(22+5.1^2)/(50-6.3^2)
disp('Part (b)')
sqrt(41^2-5.2^2)/(exp(5)-100.53)
disp('Part (c)')
cos(7*pi/9)+tan(7*pi/15)*sind(15)

Command Window:

1
2. Define the variable 𝑥 as 𝑥= 6. 7, then evaluate

a) 0.01𝑥5 − 1.4𝑥3 + 80𝑥 + 16.7


51
b) √𝑥3 + 𝑒𝑥 −
𝑥

Script file:
clc;
clear all;
x=6.7;
disp('Part (a)')
0.01*x^5-1.4*x^3+80*x+16.7
disp('Part (b)')
sqrt(x^3+exp(x)-51/x)
Command Window:

2
3. In the triangle shown a = 5. 3 in., 𝛾 = 42°, and b = 6 in. Define a, 𝛾 , and b as variables, and
then:
(a) Calculate the length c by using the Law of Cosines.
(b) Calculate the angles 𝛼 and β (in degrees) using the Law of Cosines.
(c) Check that the sum of the angles is 180°.

Script file:

clc;
clear all;
a=5.3;
gamma=42;
b=6;
disp('Part (a)')
c=sqrt(a^2+b^2-2*a*b*cosd(gamma))
disp('Part (b)')
alpha = asind(a*sind(gamma)/c)
beta = asind(b*sind(gamma)/c)
disp('Part (c)')
Total = alpha+beta+gamma

Command Window:

3
4. a) Create a row vector that has the following elements: 8, 10/4, 12 x 1.4, 51, tan85°, √26 ,
and 0.15.
0)
b) Create a column vector that has the following elements: 25.5, (14tan58
, 6!, 2.74, 0.0375, and 𝜋.
(2.12+11) 5

Script file:

clc;
clear all;
disp('Part (a)')

row=[8 10/4 12*1.4 51 tand(85) sqrt(26) 0.15]

disp('Part (b)')

col=[25.5; 14*tand(58)/(2.1^2+11); factorial(6); 2.7^4; 0.0375; pi/5]

Command Window:

4
5. Create a row vector in which the first element is 1 and the last element is 43, with an
increment of 6 between the elements (1, 7, 13, ... , 43 ).
Script file:
clc;
clear all;
row=1:6:43
Command Window:

6. a) Create the following matrix by typing one command. Do not type individual elements
explicitly.

Script file:
clc;
clear all;
%alternative C = [linspace(7,7,5); linspace(7,7,5)]
C=7*ones(2,5)
Command Window:

b) Create the following matrix by typing one command. Do not type individual elements
explicitly.

Script file:
clc;
clear all;
E=[zeros(2,5); zeros(2) [5:-1:3; 2:-1:0]]
Command Window:

5
Script file:
clc;
clear all;
a=[3 -1 5 11 -4 2];
b=[7 -9 2 13 1 -2];
c=[-2 4 -7 8 0 9];
disp('Part (a)')
matrixA=[a;b;c]
disp('Part (b)')
%alternative matrixB=[b' c' a']
matrixB=[b;c;a]'

Command Window:

6
Script file:

clc;
clear all;
M=reshape(1:18,3,6);
disp('Part (a)')
A=M([1,3],[1,5,6])
disp('Part (b)')
B=M(:,[4,4:6])
disp('Part (c)')
C=M([1,2],:)
disp('Part (d)')
D=M([2,3],[2,3]
Command Window:

7
Script file:

clc;
clear all;
disp('Part (a)')
matrixA=[ones(2) zeros(2)]
disp('Part (b)')
matrixB=[eye(2) zeros(2) ones(2)]
disp('Part (c)')
matrixC=[ones(1,4); zeros(2,4)]

Command window:

8
Script file:

clc;
clear all;
v=[15,8,-6];
u=[3,-2,6];
disp('Part (a)')
v./u
disp('Part (b)')
u'*v
disp('Part (c)')
u*v'
Command window:

9
Script file:

clc;
clear all;
u=[5,-6,9];
v=[11,7,-4];
disp('Part (a)')
dotuv=sum(u.*v)
disp('Part (b)')
dotuv=u*v'
disp('Part (c)')
dotuv=dot(u,v)

Command Window:

10
Script file:

clc;
clear all;
A=[1 -3 5; 2 2 4; -2 0 6];
B=[0 -2 1; 5 1 -6; 2 7 -1];
C=[-3 4 -1; 0 8 2; -3 5 3];
disp('Part (a)')
AplusB=A+B
BplusA=B+A
disp('Part (b)')
AplusBandC=A+(B+C)
AandBplusC=(A+B)+C
disp('Part (c)')
together=3*(A+C)
apart=3*A+3*C
disp('Part (d)')
%element by element
e_by_e_together=A.*(B+C)
e_by_e_apart=A.*B+A.*C
%matrix multiplication
mm_together=A*(B+C)
mm_apart=A*B+A*C

11
Command window:

12
Script file:

clc;
clear all;
A=10*rand(4,4)
disp('Part (a)')
disp('linear algebra multiplication')
R=A*A
disp('Part (b)')
disp('element-by-element multiplication')
R=A.*A
disp('Part (c)')
disp('linear algebra, left division (left multiply by inverse)')
R=A\A
disp('Part (d)')
disp('element-by element, right division')
R=A./A
disp('Part (e)')
disp('determinant')
R=det(A)
disp('Part (f)')
disp('inverse')
R=inv(A)

Command window:

13
14
Script file:

clc;
clear all;
close all;
x=linspace(0,2*pi,200);
f=sin(x).^2.*cos(2*x);
fp=2*sin(x).*cos(x).*cos(2*x)-2*sin(x).^2.*sin(2*x);
plot(x,f,x,fp,'--')
title('f(x)=sin^2(x)cos(2x)')
legend('f(x)','f ''(x)')
xlabel('x-->')
ylabel('y-->')

Figure Window:

15
15. Make a polar plot of the function 𝑟 = 2 sin(3𝜃) sin(𝜃) for 0 ≤ 𝜃 ≤ 2𝜋.

Script file:

clc;
clear all;
close all;
t=-4:.1:4;
theta=linspace(0,2*pi,200);
r=2*sin(3*theta).*sin(theta);
polar(theta,r)

Figure Window:

16
16. Use MATLAB to carry out the following multiplication of two polynomials:

Script File:

clc;
clear all;
pa=[-1 0 5 -1];
pb=[1 2 0 -16 5];
c=conv(pa, pb)

Command window:

17
Script file:

clc;
clear all;
p1=[1 -1.7]; p2=[1 0.5]; p3=[1 -0.7]; p4=[1 1.5]; p5=[1 0];
p12=conv(p1,p2);
p34=conv(p3,p4);
p14=conv(p12,p34);
p=conv(p14,p5)
x=linspace(-1.6,1.8,200);
y=polyval(p,x);
plot(x,y)
xlabel('x')
ylabel('y')

Command window:

18
Script File:

clc;
clear all;
pa=[-10 -20 9 10 8 11 -3];
pb=[2 4 -1];
p=deconv(pa,pb)

Command Window:

19
19a-Script File:

clc;
clear all;
close all;
x=[1 2.2 3.7 6.4 9 11.5 14.2 17.8 20.5 23.2];
y=[12 9 6.6 5.5 7.2 9.2 9.6 8.5 6.5 2.2];
p1=polyfit(x, y, 1);
xplot=linspace(0, 24,100);
yplot=polyval(p1, xplot);
plot(x, y, 'ok', xplot, yplot, 'k', 'linewidth', 2, 'markersize', 8)
xlabel('x', 'fontsize', 18)
ylabel('y', 'fontsize', 18)

Figure window:

20
19b-Script File:

clc;
clear all;
close all;
x=[1 2.2 3.7 6.4 9 11.5 14.2 17.8 20.5 23.2];
y=[12 9 6.6 5.5 7.2 9.2 9.6 8.5 6.5 2.2];
p1=polyfit(x,y,2);
xplot=linspace(0,24,100);
yplot=polyval(p1,xplot);
plot(x,y,'ok',xplot,yplot,'k','linewidth',2,'markersize',8)
xlabel('x','fontsize',18)
ylabel('y','fontsize',18)

Figure window:

21
19c-Script File:

clc;
clear all;
close all;
x=[1 2.2 3.7 6.4 9 11.5 14.2 17.8 20.5 23.2];
y=[12 9 6.6 5.5 7.2 9.2 9.6 8.5 6.5 2.2];
p1=polyfit(x,y,3);
xplot=linspace(0,24,100);
yplot=polyval(p1,xplot);
plot(x,y,'ok',xplot,yplot,'k','linewidth',2,'markersize',8)
xlabel('x','fontsize',18)
ylabel('y','fontsize',18)
Figure window:

22
19d-Script File:

clc;
clear all;
close all;
x=[1 2.2 3.7 6.4 9 11.5 14.2 17.8 20.5 23.2];
y=[12 9 6.6 5.5 7.2 9.2 9.6 8.5 6.5 2.2];
p1=polyfit(x,y,5);
xplot=linspace(0,24,100);
yplot=polyval(p1,xplot);
plot(x,y,'ok',xplot,yplot,'k','linewidth',2,'markersize',8)
xlabel('x','fontsize',18)
ylabel('y','fontsize',18)

Figure window:

23
20. Build a simple Simulink model that takes a sine wave input and amplifies it.

Simulink model:

Output:

24
PYTHON PROGRAMMING
PROCEDURE:
Step 1: Open python editor
Step 2: Write the instructions
Step 3: Save it as a file with file name having the extension .py
Step 4: Run the interpreter

FUNDAMENTAL PROGRAMMING CONCEPTS:

print() : The print() function in Python is used to output data to the console or terminal. It's a
very commonly used function in Python for displaying information, debugging, or
communicating results.

Example:

Printing a string: print("Hello, World!")

Printing multiple values:

name = "Alice"
age = 30
print("Name:", name, "Age:", age)
Output:
Name: Alice Age: 30

Using end parameter:

print("Hello", end=" ")


print("World!")
Output: Hello World!

Printing with special characters:

print("Hello\nWorld") # \n for new line


print("Hello\tWorld") # \t for tab

Input in Python: input()

Syntax: input(prompt)

25
prompt: A string that will be displayed on the screen before taking the input, letting the user
know what is expected.

Examples:

1. Taking string input:

name = input("Enter your name: ")

print("Hello, " + name)

Output:

Enter your name: Alice

Hello, Alice

2. Taking integer input:

Since input() returns a string, if you need an integer, you have to convert it using int().

age = int(input("Enter your age: "))

print(f"You are {age} years old.")

INDENTATION:

In Python, indentation is crucial because it defines the structure and flow of the code. Unlike
many other programming languages, which use braces {} or keywords to define blocks of code,
Python uses indentation to group state An Indentation Error occurs when the spacing is
inconsistent or incorrect, causing Python to fail in understanding the code's structure.

Common Causes of Indentation Error:

1. Inconsistent use of spaces and tabs: Mixing tabs and spaces in the same code block will
cause an indentation error. Python recommends using 4 spaces for indentation.

Example (incorrect):

def greet():

print("Hello,") # Indented with 4 spaces

print("World!") # Indented with 1 space (causes an error)

Fix: Ensure consistent indentation (e.g., always use 4 spaces):

26
def greet():

print("Hello,")

print("World!")

2. Indentation required for certain blocks: Python expects an indented block after specific
statements like if, for, while, def, class, etc. If you forget to indent after these statements,
you'll get an error.

Example (incorrect):

if True:

print("This will raise an error") # No indentation

Fix: Indent the block following the conditional or loop:

if True:

print("This is correct")

3. Unnecessary indentation: Adding extra, unintended indentation where it's not required
will also raise an error.

Example (incorrect):

print("This is correct")

print("This will raise an error") # Unnecessary indentation

Fix: Remove unnecessary indentation:

print("This is correct")

print("This is also correct")

4. Misalignment between blocks: If different blocks of code in the same level are not
aligned, Python will throw an error.

27
Example (incorrect):

def func():

print("Start")

print("Misaligned indentation") # Incorrect indentation level

Fix: Make sure all statements in the same block have the same indentation:

def func():

print("Start")

print("Correct indentation")

String concatenation:

In Python, string concatenation refers to combining two or more strings into one.

1. Using the + Operator

You can concatenate two or more strings using the + operator.

Example:

str1 = "Hello"

str2 = "World"

result = str1 + " " + str2

print(result)

Output: Hello World

2. Using the += Operator

The += operator allows you to append one string to another.

Example:

str1 = "Hello"
str1 += " World"
print(str1)
Output: Hello World

28
Control statements:

if:

if condition:

# block of code executed if the condition is True

You can also include elif (else if) and else statements for multiple conditions:

if condition1:

# block of code executed if condition1 is True

elif condition2:

# block of code executed if condition1 is False and condition2 is True

else:

# block of code executed if both condition1 and condition2 are False

Example:

x = 10

if x > 20:

print("x is greater than 20")

elif x == 10:

print("x is equal to 10")

else:

print("x is less than 10")

output:

x is equal to 10

while:

In Python, a while loop repeatedly executes a block of code as long as a specified condition is
True. Here's the syntax:

29
while condition:

# block of code

The loop will continue as long as the condition remains true. If the condition becomes false,
the loop stops

count = 0

while count < 5:

print("Count is:", count)

count += 1

Output:

Count is: 0

Count is: 1

Count is: 2

Count is: 3

Count is: 4

Infinite loop

Be careful with conditions that may never become false, as they can cause an infinite loop.
For example:

while True:

print("This will run forever")

Using break and continue

• break: Exits the loop immediately.


• continue: Skips the rest of the code in the current iteration and moves to the next
iteration.

Example with break:

count = 0

while count < 10:

30
if count == 5:

break

print("Count is:", count)

count += 1

Output:

Count is: 0

Count is: 1

Count is: 2

Count is: 3

Count is: 4

Example with continue:

count = 0

while count < 5:

count += 1

if count == 3:

continue

print("Count is:", count)

Output:

Count is: 1

Count is: 2

Count is: 4

Count is: 5

In this example, the number 3 is skipped due to the continue statement.

31
for:

In Python, a for loop is used to iterate over a sequence (like a list, tuple, string, or range) and
execute a block of code for each element. Here's the basic syntax:

for variable in sequence:

# block of code

Example:

fruits = ["apple", "banana", "cherry"]

for fruit in fruits:

print(fruit)

Output:

apple

banana

cherry

range() in for Loops: The range() function generates a sequence of numbers, which is
commonly used in for loops.

for i in range(5):

print(i)

Output:

The range(5) function generates numbers from 0 to 4 (5 is excluded).

32
range() with start and step arguments:

for i in range(2, 10, 2): # start at 2, end before 10, step by 2

print(i)

Output:

Iterating over a string:

for char in "Hello":

print(char)

Output:

Nested for Loops:

for i in range(3):

for j in range(2):

print(f"i: {i}, j: {j}")

33
Output:

i: 0, j: 0

i: 0, j: 1

i: 1, j: 0

i: 1, j: 1

i: 2, j: 0

i: 2, j: 1

break and continue in for loops:

• break: Exits the loop immediately.


• continue: Skips the rest of the code in the current iteration and moves to the next
iteration.

Example with break:

for i in range(5):

if i == 3:

break

print(i)

Output:

Example with continue:

for i in range(5):

if i == 2:

continue

print(i)

34
Output:

35
1.Write a program to calculate area of triangle using Heron’s formula.

(Hint: Heron's formula is given as: area = sqrt(S* (S-a)(S-b)(S-c)))

PYTHON PROGRAM:

a = float(input("Enter the first side of the triangle: "))

b = float(input("Enter the second side of the triangle: "))

c = float (input("Enter the third side of the triangle: "))

print(a,b,c)

S = (a+b+c)/2

area = (S*(S-a)*(S-b)*(S-c))**0.5

print("Area = " + str(area))

OUTPUT:

36
2. Write a program to calculate the distance between two points.

PYTHON PROGRAM:

x1 = (int(input("Enter the x coordinate of the first point : ")))

y1 = (int(input("Enter the y coordinate of the first point: ")))

x2=(int(input("Enter the x coordinate of the second point: ")))

y2 = (int(input("Enter the y coordinate of the second point: ")))

distance = ((x2-x1)**2+(y2-y1)**2)**0.5

print("Distance=")

print (distance)

OUTPUT:

37
3. Write a program to perform addition, subtraction, multiplication, division, integer division,
and modulo division on two integer numbers.

PYTHON PROGRAM:

num1 = int(input("Enter first number: "))

num2 = int(input("Enter second number: "))

add_res = num1+num2

sub_res = num1-num2

mul_res = num1*num2

idiv_res = num1/num2

modiv_res = num1%num2

fdiv_res= float(num1)//num2

print(str(num1)+" + "+str(num2)+ " = " +str(add_res))

print(str(num1)+" - "+str(num2)+ " = "+str(sub_res))

print(str(num1)+" * "+str(num2)+ " = "+str(mul_res))

print(str(num1)+" / "+str(num2)+ " = "+str(idiv_res)+"(Integer division)")

print(str(num1)+" // "+str(num2)+ " = "+str(fdiv_res)+"(float division)")

print(str(num1)+" % "+str(num2)+ " = "+str(modiv_res)+"(modulo division)")

OUTPUT:

38
4. Write a program to perform addition, subtraction, division, and multiplication on two
floating point numbers.

PYTHON PROGRAM:

num1 = float(input("Enter first number: "))

num2 = float(input("Enter second number: "))

add_res = num1+num2

sub_res = num1+num2

mul_res = num1*num2

div_res = num1/num2

print(str(num1)+" + "+str(num2)+" = "+" %.2f" %add_res)

print(str(num1)+" "+str(num2)+" = "+" %.2f"%sub_res)

print(str(num1)+" * "+str(num2)+" = "+" %.2f"%mul_res)

print(str(num1)+" / "+str(num2)+" = "+" %.2f"%div_res)

OUTPUT:

39
5. Write a program that demonstrates the use of relational operators.

PYTHON PROGRAM:

x=10

y=20

print(str(x)+" < "+str(y)+"="+str(x<y))

print(str(x)+" == "+str(y)+" = "+str(x==y))

print(str(x)+ "! = "+str(y)+" = "+str(x!=y))

print(str(x)+" > "+str(y)+" = "+str(x>y))

print(str(x)+" >= "+str(y)+" = "+str(x>=y))

print(str(x)+" <= "+str(y)+" = "+str(x<=y))

OUTPUT

40
6. Write a program to calculate area and circumference of a circle.

PYTHON PROGRAM:

radius = float (input("Enter the radius of the circle: "))

area = 3.14*radius*radius

circumference = 2*3.14*radius

print("Area = "+str(round (area, 2))+"\t Circumference ="+str(round(circumference, 2)))

OUTPUT:

41
7. Write a program to calculate average of two numbers. Print their deviation.

PYTHON PROGRAM:

num1 = int (input("Enter first number: "))

num2 =int (input("Enter second number: "))

avg = (num1+num2)/2

dev1=num1-avg

dev2 =num2-avg

print("AVERAGE", avg)

print("Deviation of first num =", dev1)

print("Deviation of second num = ", dev2)

OUTPUT:

42
8. Write a program to convert degrees Fahrenheit into degrees Celsius.

PYTHON PROGRAM:

fahrenheit = float(input("Enter the temperature in fahrenheit : "))

Celsius = (5/9) *(fahrenheit-32)

print("Temperature in degrees Celsius = ", Celsius)

OUTPUT:

Note: Degrees Celsius to Fahrenheit temperature

celsius = float(input("Enter the temperature in Celsius: "))

fahrenheit = (9/5) * celsius + 32

print("Temperature in degrees Fahrenheit =", fahrenheit)

OUTPUT:

43
9. Write a program to calculate the total amount of money in the piggybank, given the coins
of Rs 10, Rs 5, Rs 2, and Re 1.

PYTHON PROGRAM:

num_of_18_coins = int(input("Enter the number of 10Rs coins in the piggybank : "))

num_of_5_coins = int(input("Enter the number of 5Rs coins in the piggybank: "))

num_of_2_coins = int(input("Enter the number of 2Rs coins in the piggybank : "))

num_of_1_coins = int(input("Enter the number of 1Re coins in the piggybank : "))

total_amt = num_of_18_coins*10+num_of_5_coins*5+num_of_2_coins*2+num_of_1_coins

print("Total amount in the piggybank =", total_amt)

OUTPUT:

44
10. Write a program to determine whether a person is not eligible, display how many years
are left to be eligible.

PYTHON PROGRAM:

age = int(input("Enter the age : "))

if(age>=18):

print("You are eligible to vote")

else:

yrs =18-age

print("You have to wait for another " + str(yrs) +" years to cast your vote")

OUTPUT:

45
11. Write a program to find larger of two numbers.

PYTHON PROGRAM:

a = int(input("Enter the value of a: "))

b =int(input("Enter the value of b: "))

if(a>b):

large = a

else:

large = b

print("Large = ",large)

OUTPUT:

46
12. Write a program to find whether the given number is even or odd.

PYTHON PROGRAM:

num = int(input("Enter any number : "))

if(num%2==0):

print(num, "is even")

else:

print (num, "is odd")

OUTPUT:

47
13. Write a program to determine whether the character entered is a vowel or not.

PYTHON PROGRAM:

ch =input("Enter any character: ")

if(ch=="A" or ch=="E" or ch=="I" or ch=="o" or ch=="U"):

print (ch, "is a vowel")

elif(ch=="a" or ch=="e" or ch=="i" or ch=="o" or ch=="u"):

print(ch, "is a vowel")

else:

print (ch, "is not a vowel")

OUTPUT:

48
14. Write a program to calculation roots of a quadratic equation.

PYTHON PROGRAM:

a= int(input(" Enter the values of a : "))

b = int(input("Enter the values of b : "))

c = int(input("Enter the values of c : "))

D = (b*b)-(4*a*c)

deno = 2*a

if(D>0):

print("REAL ROOTS")

root1 = (-b + D**0.5)/deno

root2 = (-b - D**0.5)/deno

print("Root1 = ", root1, "\tRoot2 = ",root2)

elif(D==0):

print ("EQUAL ROOTS")

root1 = -b/deno

print("Root1 and Root2 = ",root1)

else:

print("IMAGINARY ROOTS")

OUTPUT:

49
15. Write a Program to print 0 to 10 numbers using a while loop.

PYTHON PROGRAM:

i=0

while(i<=10):

print(i, end=" ")

i = i+1

OUTPUT:

50
16. Write a program to print the reverse of a given number.

PYTHON PROGRAM:

num = int(input("Enter the number : "))

print("The reversed number is :",)

while num!=0:

temp = num%10

print(temp, end=" ")

num=num//10

OUTPUT:

51
17. Write a program using a while loop that asks the user for a number, and prints a
countdown from that number to zero.

PYTHON PROGRAM:

n = int(input("Enter the value of n : "))

while n>=0:

print(n, end = ' ')

n = n-1

OUTPUT:

52
8. Write a program using for loop to calculate factorial of a number.

PYTHON PROGRAM:

num =int(input("Enter the number : "))

if(num==0):

fact = 1

else:

fact = 1

for i in range(1, num+1):

fact = fact*i

print("Factorial of", num, "is", fact)

OUTPUT:

53
19. Write a program to print the following pattern.

**

***

****

*****

PYTHON PROGRAM:

for i in range(1,6):

print()

for j in range(i):

print("*", end=' ')

OUTPUT:

54
20. Write a program to print the following pattern.

12

123

1234

12345

PYTHON PROGRAM:

for i in range(1,6):

print()

for j in range(1,i+1):

print(j, end=' ')

OUTPUT:

55

You might also like