S.No Program No. 1 1 2 3 3 3 4 3 5 3 6 4 7 5 8 6 9 7 10 8 11 8 12 10 13 11 14 12 15 13 16 14 17 16 18 17 19 18 20 21 21 24
S.No Program No. 1 1 2 3 3 3 4 3 5 3 6 4 7 5 8 6 9 7 10 8 11 8 12 10 13 11 14 12 15 13 16 14 17 16 18 17 19 18 20 21 21 24
S.No Program No. 1 1 2 3 3 3 4 3 5 3 6 4 7 5 8 6 9 7 10 8 11 8 12 10 13 11 14 12 15 13 16 14 17 16 18 17 19 18 20 21 21 24
S.NO PROGRAM
No.
1 Introduction To Python Programming 1
2 Write a python program to print ” Hello “ message 3
Write a program to perform addition, subtraction, multiplication, division
3 3
on two input numbers
4 Write a program to calculate Employee payroll 3
5 Python program to take in the marks of 5 subjects and display the grade. 3
Python Program to Find All Odd Palindrome Numbers in a Range
6 4
without using Recursion
7 Python Program to Count the Number of Words in a Text File 5
PC352IT
Objectives:
Outcomes:
2. Analyse and implement different kinds of OOP concept in real world problems.
1 Python Variables, Executing Python from the Command Line, Editing Python Files, Python
Reserved Words
2 Comments, Strings and Numeric Data Types, Simple Input and Output.
3 Control Flow and Syntax, Indenting, if Statement, Relational Operators, Logical Operators,
Bit Wise Operators, while Loop, break and continue, for Loop, Lists, Tuples, Sets,
Dictionaries.
Functions: Passing parameters to a Function, Variable Number of Arguments, Scope,
4 Passing Functions to a Function, Mapping Functions in a Dictionary, Lambda, Modules,
Standard Modules.
OOP concepts: Classes, File Organization, Special Methods, Inheritance, Polymorphism,
5 Special Characters, Character Classes, Quantifiers, Dot Character, Greedy Matches,
Matching at Beginning or End, Match Objects, Compiling Regular Expressions.
6 MATLAB Menus, Toolbars, Computing with MATLAB, Script Files and the
Editor/Debugger, MATLAB help System.
MATLAB controls: Relational Logical Variables. Conditional Statements: if – else – elseif,
7 switch , Loops: for – while – break, continue. User-Defined Functions
8 Arrays, Matrices and Matrix Operations Debugging MATLAB Programs. Working with
Data Files, and Graphing Functions: XY Plots –Sub-plots.
Suggested Readings:
Python is developed by Guido van Rossum. Guido van Rossum started implementing Python in 1989.
Python is a very simple programming language so even if you are new to programming, you can learn
python without facing any issues.
Interesting fact: Python is named after the comedy television show Monty Python’s Flying Circus. It is
not named after the Python snake.
2. Easy to Learn: Learning python is easy as this is a expressive and high level programming language,
which means it is easy to understand the language and thus easy to learn.
3. Cross platform: Python is available and can run on various operating systems such as Mac, windows,
Linux, Unix etc. This makes it a cross platform and portable language.
5. Large standard library: Python comes with a large standard library that has some handy codes and
functions which we can use while writing code in Python.
6. Free: Python is free to download and use. This means you can download it for free and use it in your
application. Python is an example of a FLOSS (Free/Libre Open Source Software), which means you
can freely distribute copies of this software, read its source code and modify it.
7. Supports exception handling: If you are new, you may wonder what is an exception? An exception
is an event that can occur during program exception and can disrupt the normal flow of program.
Python supports exception handling which means we can write less error prone code and can test
various scenarios that can cause an exception later on.
8. Advanced features: Supports generators and list comprehensions. We will cover these features later.
9. Automatic memory management: Python supports automatic memory management which means
the memory is cleared and freed automatically. You do not have to bother clearing the memory.
You may be wondering what all are the applications of Python. There are so many applications of
Python, here are some of the them.
1. Web development – Web framework like Django and Flask are based on Python. They help you
write server side code which helps you manage database, write backend programming logic,
mapping urls etc.
2. Machine learning – There are many machine learning applications written in Python. Machine
learning is a way to write a logic so that a machine can learn and solve a particular problem on its
1
own. For example, products recommendation in websites like Amazon, Flipkart, eBay etc. is a
machine learning algorithm that recognises user’s interest. Face recognition and Voice recognition
in your phone is another example of machine learning.
3. Data Analysis – Data analysis and data visualisation in form of charts can also be developed using
Python.
4. Scripting – Scripting is writing small programs to automate simple tasks such as sending
automated response emails etc. Such type of applications can also be written in Python
programming language.
5. Game development – You can develop games using Python.
6. You can develop Embedded applications in Python.
7. Desktop applications – You can develop desktop application in Python using library like TKinter
orQT.
Python installation is pretty simple, you can install it on any operating system such as Windows, Mac
OS X, Ubuntu etc. Just follow the steps in this article – Python Installation
You can install Python on any operating system such as Windows, Mac OS X, Linux/Unix and others.
To install the Python on your operating system, go to https://www.python.org/downloads/.You will see
a screen like this.
This is the official Python website and it will detect the operating system and based on that it would
recommend you to download Python. Here I am using Mac OS X so it gave me the download options
for Python 2 and Python 3 for Mac OS X. I would recommend you to download the latest version of
Python 3 (Python 3.6.4 in the screenshot).
Installation steps are pretty simple. You just have to accept the agreement and finish the installation.
NOTE:If you are using Mac OS X then you may notice that Python is already installed in your system,
however it would most likely be a Python 2 so you can download the latest Python 3 version from here
and install it in your system.
2
MJCET IT WORKSHOP
print('Hello,world!')
# ##Python has very simple syntax. You can start write your code directly, i.e.,no main funtion
inpython.Print()function prints the given object inscreen or device.###
Sample Input
5
5
Sample Output
10
0
25
1
SampleInput:
300
30
Sample Output:
4. Python program to take in the marks of 5 subjects and display the grade.
This is a Python Program to take in the marks of 5 subjects and display the grade.
Problem Description
The program takes in the marks of 5 subjects and displays the grade.
Problem Solution
1. Take in the marks of 5 subjects from the user and store it in different variables.
2. Find the average of the marks.
3. Use an else condition to decide the grade based on the average of the marks.
4. Exit.
3
MJCET IT WORKSHOP
Program/SourceCode
Source code of the Python Program to take in the marks of 5 subjects and display the grade.
Program Explanation
Sample Output
Case1:
Enter marks of the first subject: 85
Enter marks of the second subject: 95
Enter marks of the third subject: 99
Enter marks of the fourth subject: 93
Enter marks of the fifth subject: 100
Grade: A
Case2:
Enter marks of the first subject: 81
Enter marks of the second subject: 72
Enter marks of the third subject: 94
Enter marks of the fourth subject: 85
Enter marks of the fifth subject: 80
Grade: B
5. Python Program to Find All Odd Palindrome Numbers in Range with out using Recursion
This is a Python Program to find all numbers which are odd and palindromes between arrange of
numbers without using recursion.
4
MJCET IT WORKSHOP
Problem Description
The program takes arrange and prints all numbers which are odd and palindromes between the range
without using recursion.
Problem Solution
1. Take a upper limit and lower limit from the user.
2. Using list comprehension, store all the numbers in the list that are odd and palindromes.
3. Print the list.
4. Exit.
a=[]
l=int(input("Enter lower limit: "))
u=int(input("Enterupperlimit:"))
a=[x for x in range(l,u+1)if x%2!=0 and str(x)==str(x)[::-1]]
print("Thenumbersare:",a)
Program Explanation
Sample Output:
Case1:
Enter lower limit: 100
Enter upper limit: 150
The numbers are: [101,111,121,131,141]
Case2:
Enter lower limit: 300
Enter upper limit: 400
The numbers are: [303,313,323,333,343,353,363,373,383,393]
Problem Description
The program takes the filename from the user and counts number of words in that file.
Problem Solution
1. Take the filename from the user.
2. Read each line from the file and split the line to forma list of words.
3. Find the length of items in the list and print it.
4. Exit.
Program/Source Code
fname= input("Enterfilename:")
num_words=0
with open(fname,'r')as f:
for line in f:
words= line.split()
num_words+=len(words)
print("Numberofwords:")
print(num_words)
5
MJCET IT WORKSHOP
Program Explanation
Sample Output
Case1:
Contents of file:
Hello world
Output:
Enter file name: data1.txt
Number of words: 2
Case2:
Contents of file:
This programming language is Python
Output:
Enter file name: data2.txt
Number of words: 5
Problem Description
The program takes a number n and prints and computes the series“1+2+…+n=”.
Problem Solution
Program/Source Code
Program Explanation
6
MJCET IT WORKSHOP
Sample Output
Case1:
Enter a number: 4
1 +2 +3+4=10
Case2:
Enter a number: 5
1+2+3+4+5=15
8. Python Program to Find the Second Largest Number in a List using Bubble Sort
Problem Description
The program takes a list and finds the second largest number in the list using bubblesort.
Problem Solution
1. Take in the number of elements for the list and store it in a variable.
2. Take in the elements of the list one by one.
3. Then sort the list using bubble sort.
4. Print these cond last element of the sorted list which is these cond-largest number.
5. Exit.
Program/Source Code
a=[]
n=int(input("Enter number of elements:"))
for i in range(1,n+1):
b=int(input("Enter element:"))
a.append(b)
for i in range(0,len(a)):
for j in range(0,len(a)-i-1):
if(a[j]>a[j+1]):
temp=a[j]
a[j]=a[j+1]
a[j+1]=temp
print('Second largest number is:',a[n-2])
Program Explanation
1. User must enter the number of elements for the list and store it in a variable.
2. User must then enter the elements of the list one by one using a for loop and store it in a list.
3. Then bubble sort algorithm may be used to sort the elements of the list.
4. These second last element of the sorted list is then printed which is basically these second
largest element in the list.
Sample Output
Case1:
Enter number of elements: 4
Enter element: 56
Enter element: 43
Enter element: 78
Enter element: 12
Second largest number is: 56
Case2:
Enter number of elements: 6
Enter element: 23
Enter element: 45
Enter element: 94
Enter element: 10
Enter element: 34
7
MJCET IT WORKSHOP
Enter element: 95
Second largest number is: 94
Problem Description
The program takes in the number of terms and finds the sum of series: 1+ 1/2+1/3+ …..+ 1/N.
Problem Solution
1. Take in the number of terms t of ind the sum of the series for.
2. Initialize the sum variable to 0.
3. Use a for loop ranging from1 to the number and find the sum of the series.
4. Print the sum of these ries after rounding it of f to t wodecimal places.
5. Exit.
Program/Source Code
Program Explanation
Sample Output
Case1:
Enter the number of terms: 7
The sum of series is
2.59
Case2:
Enter the number of terms: 15
The sum of series is 3.32
10. Python Program to Print Largest Even and Largest Odd Number in a List
Problem Description
The program takes in a list and prints the largest even and largest off number in it.
Problem Solution
8
MJCET IT WORKSHOP
Program/Source Code
c=[]
d=[]
for i in b:
if(i%2==0):
c.append(i)
else:
d.append(i)
c.sort()
d.sort()
count1=0
count2=0
for k in c:
count1=count1+1
for j in d:
count2=count2+1
print("Largest even number:",c[count1-1])
print("Largest odd number",d[count2-1])
Program Explanation
Sample Output
Case1:
Enter the number of elements to be in the list:5
Element:45
Element:20
Element:80
Element:93
Element: 3
Largest even number:80
Largest odd number 93
Case2:
Enter the number of elements to be in the list:4
Element:23
Element:10
Element:34
Element:89
Largest even number: 34
Largest odd number 89
9
MJCET IT WORKSHOP
11. Python Program to Print Numbers in a Range Without using Loops or using functions
Problem Description
The program takes in the upper limit and prints all numbers within the given range using recursive
function.
Problem Solution
1. Define a recursive function.
2. Define a base case for that function that the number should be greater than zero.
3. If number is greater than 0, call the function again with the argument as the number minus1.
4. Print the number.
5. Exit.
Program/Source Code
def printno(upper):
if(upper>0):
printno(upper-1)
print(upper)
upper=int(input("Enter upper limit: "))
printno(upper)
Program Explanation
1. User must enter the upper limit of the range.
2. This value is passed as an argument for the recursive function.
3. The base case for the recursive function is that number should always be greater than 0.
4. Ifnumberisgreaterthan0, function is called again with the argument as the number minus1.
5. The number is printed.
6. The recursion continues until the number becomes lesserthan0.
Sample Output
Case1:
Enter upper limit: 5
1
2
3
4
5
Case2:
Enter upper limit: 15
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
10
MJCET IT WORKSHOP
Problem Description
The program takes two lists, merges the m and sorts the merged list.
Problem Solution
1. Take in the number of elements for the first list and store it in a variable.
2. Take in the elements of the list one by one.
3. Similarly, take in the elements for these second list also.
4. Merge both the lists using the ‘+’ operator and then sort the list.
5. Display the elements in the sorted list.
6. Exit.
Program/Source Code
a=[]
c=[]
n1=int(input("Enter number of elements:"))
for i in range(1,n1+1):
b=int(input("Enter element:"))
a.append(b)
n2=int(input("Enter number of elements:"))
for i in range(1,n2+1):
d=int(input("Enter element:"))
c.append(d)
new=a+c.sort()
print("Sorted listis:",new)
Program Explanation
1. User must enter the number of elements for the first list and store it in a variable.
2. User must the n enter the elements of the list one by one using a for loop and store it in a
list.
3. User must similarly enter the elements of the second list one by one.
4. The ‘+’ operator is then used to merge both the lists.
5. The sort function then sorts the list in ascending order.
6. The sorted list is then printed.
Sample Output
Case1:
Enter number of elements: 5
Enter element: 10
Enter element: 20
Enter element: 35
Enter element: 55
Enter element: 71
Enter number of elements: 2
Enter element: 5
11
MJCET IT WORKSHOP
Enter element: 37
Sorted list is: [5, 10, 20, 35, 37, 55, 71]
Case2:
Enter number of elements: 3
Enter element: 2
Enter element: 4
Enter element: 8
Enter number of elements: 3
Enter element: 2
Enter element: 4
Enter element: 0
Sorted list is:[0, 2, 2, 4, 4, 8]
13. Python Program to Split Even and Odd Elements into Two Lists
Problem Description
The program takes a list and puts the even and odd elements in it into two separate lists.
Problem Solution
Program/Source Code
a=[]
n=int(input("Enter number of elements:"))
for i in range(1,n+1):
b=int(input("Enter element:"))
a.append(b)
even=[]
odd=[]
for j in a:
if(j%2==0):
even.append(j)
else:
odd.append(j)
print("The even list",even)
print("The odd list",odd)
12
MJCET IT WORKSHOP
Program Explanation
Sample Output
Case1:
Enter number of elements: 5
Enter element: 67
Enter element: 43
Enter element: 44
Enter element: 22
Enter element: 455
The even list [44, 22]
The odd list [67, 43,455]
Case2:
Enter number of elements: 3
Enter element: 23
Enter element: 44
Enter element: 99
The even list [44]
The odd list [23, 99]
14. Python Program to Count the Occurrences of Each Word in a Given String Sentence
Problem Description
The program takes a string and counts the occurrence of each word in the given sentence.
Problem Solution
1. Take a string and a word from the user and store it in separate variables.
2. Initialize a count variable to 0.
3. Split the string using space as the reference and store the words in a list.
4. Use a for loop to traverse through the words in the list and use an if statement to
check if the word in the list matches the word given by the user and increment the
count.
5. Print the total count of the variable.
6. Exit.
13
MJCET IT WORKSHOP
Program/Source Code
string=raw_input("Enter string:")
word=raw_input("Enter word:")
a=[]
count=0
a=string.split(" ")
for i in range(0,len(a)):
if(word==a[i]):
count=count+1
print("Count of the word is:")
print(count)
Program Explanation
1. User must enter a string and a word and store it in separate variables.
2. The count variable is initialized to zero.
3. The string is split in to words using space as the reference and stored in a list.
4. The for loop is used to traverse through the words in the list.
5. The count is incremented each time the word in the list is equal to the word given by the
user.
6. The total count of the word is printed.
Sample Output
Case1:
Enter string: hello world
Enter word: hello
Count of the word is:
1
Case2:
Enter string: orange blue red orange
Enter word: orange
Count of the word is:
2
Problem Description
The program takes two lists and maps two lists into a dictionary.
Problem Solution
keys=[]
values=[]
n=int(input("Enter number of elements for dictionary:"))
print("For keys:")
for x in range(0,n):
element=int(input("Enter element" + str(x+1) + ":"))
keys.append(element)
print("For values:")
for x in range(0,n):
element=int(input("Enter element" + str(x+1) + ":"))
values.append(element)
d=dict(zip(keys,values))
print("The dictionary is:")
print(d)
Program Explanation
1. User must enter the number of elements in the list and store it in avariable.
2. User must enter the values to the same number of elements in to the list.
3. The append function obtain seach element from the user and adds the same to the end of
the list as many times as the number of elements taken.
4. The same of 2 and 3 is done for the second values list also.
5. The two lists are merged to gether using the zip() function.
6. The zipped lists are then merged to form a dictionary using dict().
7. The dictionary formed from the two lists is then printed.
Sample Output
Case1:
Enter number of elements for dictionary: 3
For keys:
Enter element1:1
Enter element2:2
Enter element3:3
For values:
Enter element1:1
Enter element2:4
Enter element3:9
15
MJCET IT WORKSHOP
Case2:
Enter number of elements for dictionary:5
For keys:
Enter element1:1
Enter element2:2
Enter element3:3
Enter element4:4
Enter element5:5
For values:
Enter element1:78
Enter element2:65
Enter element3:34
Enter element4:100
Enter element5:1000
The dictionary is:
{1: 78, 2: 65, 3: 34, 4: 100, 5: 1000}
Problem Description
The program takes a dictionary and removes a given key from the dictionary.
Problem Solution
Program/Source Code
d= {'a':1,'b':2,'c':3,'d':4}
print("Initial dictionary")
print(d)
key=raw_input("Enter the key to delete(a-d):")
if key in d:
del d[key]
else:
print("Key not found!")
exit(0)
print("Updated dictionary")
print(d)
16
MJCET IT WORKSHOP
Program Explanation
Sample Output
Case1:
Initial dictionary
{'a': 1, 'c': 3, 'b': 2, 'd': 4}
Enter the key to delete(a-d):a
Updated dictionary
{'c': 3, 'b': 2, 'd': 4}
Case2:
Initial dictionary
{'a':1,'c':3,'b':2,'d':4}
Enter the key to delete (a-d): g
Key not found!
17. Python Program that Displays Letters that are not Common in Two Strings
Problem Description
The program takes two strings and displays which letters are in the two strings but not in both.
Problem Solution
Program/Source Code
17
MJCET IT WORKSHOP
Program Explanation
1. User must enter two input strings and store it in separate variables.
2. Both of the strings are converted into sets and the letters which are present in the two
strings but not in both are found using the ‘^’ operator.
3. These letters are stored in a list.
4. A for loop is used to print the letters of the list.
Case2:
Enter first string:hello
Enter second string:World
The letters are:
e
d
h
r
W
18. Python Program to Create a Class which Performs Basic Calculator Operations
Problem Description
The program takes the input from the user and performs operation using classes.
Problem Solution
class cal():
def init(self,a,b):
18
MJCET IT WORKSHOP
self.a=a
self.b=b
def add(self,a,b):
return a+b
def mul(self,a,b):
return a*b
def div(self,a,b):
return a/b
def sub(self,a,b):
return a-b
a=int(input("Enter first number:"))
b=int(input("Enter second number: "))
obj=cal()
choice=1
while choice!=0:
print("0.Exit")
print("1.Add")
print("2. Subtraction")
print("3.Multiplication")
print("4.Division")
choice=int(input("Enter choice:"))
if choice==1:
print("Result:",obj.add(a,b))
elif choice==2:
print("Result:",obj.sub(a,b))
elif choice==3:
print("Result:",obj.mul(a,b))
elif choice==4:
print("Result:",round(obj.div(a,b),2))
elif choice==0:
print("Exiting!")
else:
print("Invalid choice!!")
print()
Program Explanation
1. A class called cal is created and the init() method is used to initialize values of that class.
2. Methods for adding, substracting, multiplying, dividing two numbers and returning the
irrespective results are defined.
3. The menu is printed and the choice is taken from the user.
4. An object for the class is created with the two numbers taken from the user passed
as parameters.
5. Using the object, the respective method is called according to the choice taken from the user.
6. Whenthechoiceis0,the loop is exited.
7. The final result is printed.
19
MJCET IT WORKSHOP
Enter choice:1
('Result:', 4)
0.Exit
1.Add
2. Subtraction
3.Multiplication
4.Division
Enter choice:2
('Result:', -2)
0.Exit
1.Add
2. Subtraction
3.Multiplication
4.Division
Enter choice:3
('Result:', 3)
0.Exit
1.Add
2. Subtraction
3.Multiplication
4.Division
Enter choice:4
('Result:', 0.0)
0.Exit
1.Add
2. Subtraction
3.Multiplication
4.Division
Enter choice:5
Invalid choice!!
0.Exit
1.Add
2. Subtraction
3.Multiplication
20
MJCET IT WORKSHOP
4.Division
Enter choice:0
Exiting!
19. Python Program to Append, Delete and Display Elements of a List using Classes
Problem Description
The program appends, deletes and displays elements of a list using classes.
Problem Solution
class check():
def init(self):
self.n=[]
def add(self,a):
return self.n.append(a)
def remove(self,b):
self.n.remove(b)
def dis(self):
return(self.n)
obj=check()
choice=1
while choice!=0:
print("0.Exit")
print("1. Add")
print("2. Delete")
print("3.Display")
choice=int(input("Enter choice:"))
if choice==1:
n=int(input("Enter number to append: "))
obj.add(n)
print("List:",obj.dis())
elif choice==2:
n=int(input("Enter number to remove:"))
obj.remove(n)
print("List:",obj.dis())
21
MJCET IT WORKSHOP
elif choice==3:
print("List:",obj.dis())
elif choice==0:
print("Exiting!")
else:
print("Invalid choice!!")
Program Explanation
1. A class called check is created and the init() method isused to initialize values of that
class.
2. Methods for adding, removing and displaying elements of the list have been defined.
3. The menu is printed and the choice is taken from the user.
4. An object for the class is created.
5. Using the object, the respective method is called according to the choice taken from the user.
6. The final list is printed.
Case 1:
0. Exit
1. Add
2. Delete
3. Display
Enter choice: 1
Enter number to append: 23
List: [23]
0. Exit
1. Add
2. Delete
3. Display
Enter choice: 1
Enter number to append: 45
List: [23, 45]
0. Exit
1. Add
2. Delete
3. Display
Enter choice: 1
Enter number to append: 56
List: [23, 45, 56]
0. Exit
1. Add
2. Delete
22
MJCET IT WORKSHOP
3. Display
Enter choice: 2
Enter number to remove: 45
List: [23, 56]
0. Exit
1. Add
2. Delete
3. Display
Enter choice: 0
Exiting!
Case 2:
0. Exit
1. Add
2. Delete
3. Display
Enter choice: 1
Enter number to append: 10
List: [10]
0. Exit
1. Add
2. Delete
3. Display
Enter choice: 1
Enter number to append: 7
List: [10,7]
0. Exit
1. Add
2. Delete
3. Display
Enter choice: 0
Exiting!
23
MJCET IT WORKSHOP
INTRODUCTION TO MATLAB
What Is MATLAB
MATLAB is an interactive system whose basic data element is an array that does not require
dimensioning. This allows you to solve many technical computing problems, especially those
with matrix and vector formulations, in a fraction of the time it would take to write a program in
a scalar non interactive language such as C or Fortran.
The name MATLAB stands for matrix laboratory. MATLAB was originally written to provide
easy access to matrix software developed by the LINPACK and EISPACK projects, which
together represent the state-of-the-art in software for matrix computation.
MATLAB has evolved over a period of years with input from many users. In university
environments, it is the standard instructional tool for introductory and advanced courses in
mathematics, engineering, and science. In industry, MATLAB is the tool of choice for high-
productivity research, development, and analysis.
Handle Graphics.
This is the MATLAB graphics system. It includes high-level commands for two-dimensional
24
MJCET IT WORKSHOP
To obtain help on any of the MATLAB commands, you simply need to type
help <command>
at the command prompt. For example, to obtain help on the gamma function, we type at the
command prompt:
help gamma
Try this now. You may also get help about commands using the "Help Desk", which can be
accessed by selecting the MATLAB Help option under the Help menu.
Note that the description MATLAB returns about the command you requested help on contains
the command name in ALL CAPS. This does not mean that you use this command by typing it
in ALL CAPS. In MATLAB, you almost always use all lower case letters when using a
command.
Variables in MATLAB
We can easily define our own variables in MATLAB. Let's say we need to use the value of
3.5sin(2.9) repeatedly. Instead of typing 3.5*sin(2.9)over and over again, we can denote this
variable as x by typing the following:
x=3.5*sin(2.9)
(Please try this in MATLAB.) Now type
x+1
and observe what happens. Note that we did not need to declare x as a variable that is supposed
to hold a floating point number as we would need to do in most programming languages.
Often, we may not want to have the result of a calculation printed-out to the command window.
To supress this output, we put a semi-colon at the end of the command; MATLAB still performs
the command in "the background". If you defined x as above, now type
y=2*x;
y
and observe what happened.
In many cases we want to know what variables we have declared. We can do this by
typing whos. Alternatively, we can view the values by openning the "Workspace" window. This
is done by selecting the Workspace option from the View menu. If you want to erase all
25
MJCET IT WORKSHOP
variables from the MATLAB memory, type clear. To erase a specific variable, say x, type clear
x. To clear two specific variables, say x and y, type clear x y, that is separate the different
variables with a space. Variables can also be cleared by selecting them in the Workspace
window and selecting the delete option
Example 1: Plot sin(x2) on the interval [-5,5]. To do this, type the following:
x=-5:0.01:5;
y=sin(x.^2);
plot(x,y)
and observe what happens.
Example 2: Plot exp(sin(x)) on the interval [-p,p]. To do this, type the following:
x=linspace(-pi,pi,101);
y=exp(sin(x));
plot(x,y)
and observe what happens. The command line space creates a vector of 101 equally spaced
values between -p and p (inclusive).
Ocassionally, we need to plot values that vary quite differently in magnitude. In this case, the
regular plot command fails to give us an adequate graphical picture of our data. Instead, we need
a command that plots values on a log scale. MATLAB has 3 such commands: loglog, semilogx,
and semilogy. Use the help command to see a description of each function. As an example of
where we may want to use one of these plotting routines, consider the following problem:
Example 3: Plot x5/2 for x = 10-5 to 105. To do this, type the following:
x=logspace(-5,5,101);
y=x.^(5/2);
plot(x,y)
and observe what happens. Now type the following command:
loglog(x,y)
The command logspace is similar to linspace, however it creates a vector of 101 points
lograthmically equally distributed between 10-5 and 105.
26
MJCET IT WORKSHOP
a = 3;
b = 5;
c = a+b
Output: 8
a = 3;
b = 9;
c = 2*a+b^2-a*b+b/a-10
Output: 53
Output
3 square equals 9
3 cube equals 27
The square root of 3 is 1.7321
x = pi;
y = sin(pi/2)
z = exp(-sin(pi/2))
27
MJCET IT WORKSHOP
Output
y=1
z = 0.3679
b = 3;
for k = 1:5
b
end
Output: 3 3 3 3 3
23. c. if command
num1 = 7;
if (num1 > 5)
fprintf('%4u is greater than 5 \r', num1)
else
fprintf('%4u is less than or equal to 5 \r', num1)
end
num1 = 4;
if (num1 >= 5)
fprintf('%4i is greater than or equal to 5 \r', num1)
elseif (num1 > 1)
fprintf('%4i is less than 5 but greater than 1 \r', num1)
elseif (num1 == 1)
fprintf('%4i equals 1 \r', num1)
elseif (num1 > -3)
fprintf('%4i is less than 1 but greater than -3 \r', num1)
else
fprintf('%4i is less than or equal to -3 \r', num1)
end
a = [2 12 25];
28
MJCET IT WORKSHOP
b = [3 7 4];
c = a+b
Output
c = 5 19 29
a = [2 3; 1 4];
b = [5 1; 7 2];
c = a.*b
Output
c = 10 3
5 8
24. a. Element-by-element multiplication involving two 1-D arrays or two matrices of the
same dimension
a = [2 3 5];
b = [2 4 9];
c = a.*b
Output
c = 4 12 45
a = [2 3 5];
b = sin(a)
Output
A = [4 1 2; 0 3 1; 0 1 2];
b = [17 ; 19 ; 13];
x = inv(A)*b
Output
x=154
29
MJCET IT WORKSHOP
r=input(‘enter Radius’);
a=pi*r*r;
fprintf(‘area of circle is %f” , a);
Sample output
12
Area of circle is 452.19
Sample output:
a=input(‘enter x1 value’);
b=input(‘enter x2 value’);
c=input(‘enter y1 value’);
d=input(‘enter y2 value’);
e= sqrt(((x2-x1)^2+((y2-y1)^2))
Sample output:
enter x1 value 2
enter x2 value 3
enter y1 value 4
enter y2 value 5
e = 1.414
30
MJCET IT WORKSHOP
x = linspace(0,10,100);
y = exp(x/10).*sin(4*x);
plot(x,y,'-o')
plot(x,y,'o')
Sample output:
x = linspace(0,10,50);
y = sin(x);
plot(x,y,'-s','MarkerSize',10,...
'MarkerEdgeColor','red',...
'MarkerFaceColor',[1 .6 .6])
Sample output
31
MJCET IT WORKSHOP
27. a. write a program to demonstrate two graph with diff input sin and cos
x = linspace(-2*pi,2*pi);
y1 = sin(x);
y2 = cos(x);
plot(x,y1,x,y2)
Sample output:
32
MJCET IT WORKSHOP
x = linspace(0,10,150);
y = cos(5*x);
plot(x,y,'Color',[0,0.7,0.9])
title('2-D Line Plot')
xlabel('x')
ylabel('cos(5x)')
Sample output
33