MATLAB MANUAL 7th SEM (ME - 705)
MATLAB MANUAL 7th SEM (ME - 705)
LABORATORY FILE
ME705
MATLAB R PROGRAMMING
SUBMITTED BY
Abhinav Kumar
Enrollmentno: 0198ME201003
B.Tech. VII Semester
Index
10. Write a program to read a string, then replace each character in the
string with its following character in ASCII code*.)
LabManual
OBJECTIVES:
To make the students learn concepts like MATLAB and R variable,data types,operators,loops etc.
Institute based on quality Outcome Based Education that empowers the young generation with
Knowledge,Skills,Research,Aptitude and Ethical values to solve Contemporary Challenging Problems.
Develop a platform for achieving globally acceptable level of intellectual acumen and technological competence
Create an inspiring ambience that raises the motivation level for conducting quality research Provide an environment for
acquiring ethical values and positive attitude
To spark the imagination of the MECHANICAL ENGINEERING with values,skills and creativity to solve the
real world problems.
To inculcate creative thinking and problem solving skills through effective teaching,learning and research.To empower
professionals with core competency in the field of MECHANICAL ENGINEERING.
.
Do’s
1. Come with completed observation and record
3. Know the location of the fire extinguisher and the first aid box and how to use the min case of an
emergency.
4. Read and understand how to carry out an activity thoroughly before coming to the laboratory. 5.Report
any broken plugs or exposed electrical wires to your lecturer/laboratory technician immediately.
Don’ts
1. Do not eat or drink in the laboratory.
2. Do not operate mobile phones in the lab.Keep mobile phones either in silent or switched off mode.
Introduction:-
MATLAB tutorial is prepared for complete beginners to MATLAB. Our MATLAB tutorial provides excellent insight into
the core fundamentals of MATLAB. By learning the core concepts of MATLAB, a core learner can go further to our
advance MATLAB tutorial in the path of learning the MATLAB.
Desktop Tools
1- Command Window: Use the Command Window to enter variables and run functions and M-files.
2- Command History: Statements you enter in the Command Window are logged in the Command History. In
the Command History, you can view previously run statements, and copy and execute selected statements.
3- Current Directory Browser: MATLAB file operations use the current directory reference point. Any file
you want to run must be in the current directory or on the search path.
4- Workspace: The MATLAB workspace consists of the set of variables (named arrays) built up during a
MATLAB session and stored in memory.
Basic Commands
• clear Command: Removes all variables from workspace.
• clc Command: Clears the Command window and homes the cursor.
• help Command: help displays help about that Topic if it exist.
• lookfor Command: Provides help by searching through all the first lines of MATLAB help topics and returning those that
contains a key word you specify.
• edit Command: enable you to edit (open) any M-file in Editor Window. This command doesn’t open built-in function like,
sqrt. See also type Command.
• more command: more on enables paging of the output in the MATLAB command window, and more off disables paging of
the output in the MATLAB command window.
EXPERIMENT-2
AIM:- Working with matrices.
Working with Matrices
The best way for you to get started with MATLAB is to learn how to handle matrices. You only have to follow
• Surround the entire list of elements with square brackets, [ ]. For Example >> A = [16 3 2 13; 5 10 11 8; 9 6 7 12; 4 15
14 1]
A=
16 3 2 13
5 10 11 8
9 6 7 12
4 15 14 1
Once you have entered the matrix, it is automatically remembered in the MATLAB workspace. You can refer
to it simply as A. Also you can enter and change the values of matrix elements by using workspace window.
Subscripts
The element in row i and column j of A is denoted by A(i,j). For example, A(4,2) is the number in the
fourth row and second column. For the above matrix, A(4,2) is 15. So to compute the sum of the elements
in the fourth column of A, type >> A(1,4) + A(2,4) + A(3,4) + A(4,4) ans = 34
You can do the above summation, in simple way by using sum command. If you try to use the value of an
size increases to accommodate the newcomer. The initial values of other new elements are zeros. >> X
= A;
>> X(4,5) = 17
X = 16 3 2 13 0
5 10 11 8 0
4 15 14 1 17
Colon Operator
The colon " : " is one of the most important MATLAB operators. It occurs in several different forms. The expression
>> 1:10 is a row vector containing the integers from 1 to 10 1 2 3 4 5 6 7 8 9 10 To obtain non unit spacing, specify
>> 100:-7:50
100 93 86 79 72 65 58 51
EXPERIMENT-3 AIM :-
Rational and logical operation of MATLAB.
.
Relational and Logical Operations These operations and functions provide answers to True-False questions. One important use
of this capability is to control the flow or order of execution of a series of MATLAB commands (usually in an M-file ) based on
the results of true/false questions. As inputs to all relational and logical expressions, MATLAB considers any nonzero number to
be true, and zero to be False. The output of all relational and logical expressions produces one for True and zero for False, and
the array is flagged as logical. That is, the result contains numerical values 1 and 0 that can be used in mathematical statement,
but also allow logical array addressing.
Relational Operations
Operation Description
== Equal
~= Not equal
< Less than
> Greater than
Example:
>> a=1:9; b=9-a;
>> t=a>4 %finds elements of (a) that are greater than 4.
t=000011111
Zeros appear where a ≤ 4, and ones where a > 4.
>> t= (a==b) %finds elements of (a) that are equal to those in (b).
t=000000000
Operation Description
Logical Operation:-
Operation Description
& Logical AND and(a,b)
I Logical OR or(a,b)
~ Logical NOT
xor (a,b) Logical EXCLUSIVE OR
Example:
>> a = [0 4 0 -3 -5 2];
>> b = ~a b = 1 0 1 0 0 0
>> c=a&b
c = 0 0 0 0 0 0 Example:
let x=[ 2 -3 5 ;0 11 0], then
a) find elements in x that are greater than 2
b) find the number of nonzero elements in x solution
Name Enrollmentno: Collegename
9
TRINITYINSTITUTEOFTECHNOLOGY &RESEARCH,BHOPAL
Department of Mechanical Engineering
a) >> x>2 ans = 0 0 1
010
b) >> t=~(~x);
>> sum(sum(t))
ans = 4
Bitwise Operation
MATLAB also has a number of functions that perform bitwise logical operations. If A, B unsigned integers then:
Logical Functions
MATLAB has a number of useful logical functions that operate on scalars, vectors, and matrices. Examples are given in the
following list:-
Function Description
any(x) True if any element of a vector is a nonzero number or is
logical 1 (TRUE)
all(x) True if all elements of a vector are nonzero.
find(x) Find indices of nonzero elements
EXPERIMENT-4
AIM:- Creating a plot using Plot function.
MATLAB has extensive facilities for displaying vectors and matrices as graphs, as well as annotating and printing these graphs.
x = 0:pi/100:2*pi;
y = sin(x);
plot(y)
The subplot command enables you to display multiple plots in the same window or
subplot(m,n,p)
partitions the figure window into an m-by-n matrix of small subplots and selects the pth
subplot for the current plot. The plots are numbered along first the top row of the figure
window, then the second row, and so on. For example, these statements plot data in four
t = 0:pi/10:2*pi;
subplot(2,2,1); plot(x)
subplot(2,2,2); plot(y)
subplot(2,2,3); plot(z)
subplot(2,2,4); plot(v)
EXPERIMENT-5
AIM:- Numbers and strings (1.Write a program in M-File to read 3 x 3 Matrix, then
display the diagonal of matrix as shown below: The Diagonal of This Matrix = [ ].
Matrices and Arrays
MATLAB is an abbreviation for "matrix laboratory." While other programming languages mostly work with numbers one at a
time, MATLAB® is designed to operate primarily on whole matrices and arrays.
All MATLAB variables are multidimensional arrays, no matter what type of data. A matrix is a two-dimensional array often used
for linear algebra.
Array Creation
To create an array with four elements in a single row, separate the elements with either a comma (,) or a space.
a = [1 2 3 4]
a = 1×4
1 2 3 4
1 3 5
2 4 6
7 8 10
Another way to create a matrix is to use a function, such as ones, zeros, or rand. For example, create a 5-by-1 column
vector of zeros.
z = zeros(5,1)
z = 5×1
0
0
0
0
0
Matrix and Array Operations
MATLAB allows you to process all of the values in a matrix using a single arithmetic operator or function.
a + 10
sin(a)
ans =
3×3
1 2 7
3 4 8
5 6 10
D = diag( v ) returns a square diagonal matrix with the elements of vector v on the main
diagonal. D = diag( v , k ) places the elements of vector v on the k th diagonal. k=0 represents
the main diagonal, k>0 is above the main diagonal, and k<0 is below the main diagonal.
MV = diag(V)
MV = diag(V,K)
EXPERIMENT-6
What is R
R is a popular programming language used for statistical computing and graphical presentation. Its most
common use is to analyze and visualize data. R is an open-source programming language that is widely
used as a statistical software and data analysis tool. R generally comes with the Command-line interface. R
is available across widely used platforms like Windows, Linux, and macOS. Also, the R programming
language is the latest cutting-edge tool.
It was designed by Ross Ihaka and Robert Gentleman at the University of Auckland, New Zealand, and is
currently developed by the R Development Core Team. R programming language is an implementation of the
S programming language. It also combines with lexical scoping semantics inspired by Scheme. Moreover,
the project conceives in 1992, with an initial version released in 1995 and a stable beta version in 2000.
Why Use R?
• It is a great resource for data analysis, data visualization, data science and machine
learning
TRINITYINSTITUTEOFTECHNOLOGY &RESEARCH,BHOPAL
Department of Mechanical Engineering
• It provides many statistical techniques (such as statistical tests, classification,
clustering and data reduction)
• It is easy to draw graphs in R, like pie charts, histograms, box plot, scatter plot, etc++
• It works on different platforms (Windows, Mac, Linux)
• It is open-source and free
• It has a large community support
• It has many packages (libraries of functions) that can be used to solve different
problems
Advantages of R:
• R is the most comprehensive statistical analysis package. As new technology and concepts often appear
first in R.
• As R programming language is an open source. Thus, you can run R anywhere and at any time.
• R programming language is suitable for GNU/Linux and Windows operating system.
• R programming is cross-platform which runs on any operating system.
• In R, everyone is welcome to provide new packages, bug fixes, and code enhancements.
• Basic Statistics: The most common basic statistics terms are the mean, mode, and median. These are
all known as “Measures of Central Tendency.” So using the R language we can measure central
tendency very easily.
• Static graphics: R is rich with facilities for creating and developing interesting static graphics. R contains
functionality for many plot types including graphic maps, mosaic plots, biplots, and the list goes on.
• Probability distributions: Probability distributions play a vital role in statistics and by using R we can
easily handle various types of probability distribution such as Binomial Distribution, Normal Distribution,
Chi-squared Distribution and many more.
• Data analysis: It provides a large, coherent and integrated collection of tools for data analysis.
EXPERIMENT-7
AIM:- Write R Data Types, Arithmetic & Logical Operators with Example .
Data Types
In programming, data type is an important concept.Variables can store data of different types, and
different types can do different things.In R, variables do not need to be declared with any
particular type, and can even change type after they have been set:
Example
We can use the class() function to check the data type of a variable:
# numeric
x <- 10.5
class(x)
# integer
x <- 1000L
class(x)
# complex
x <- 9i +
3 class(x)
# character/string x
<- "R is exciting"
class(x)
# logical/boolean
x <- TRUE class(x)
Operators
Operators are used to perform operations on variables and values. we use the + operator to add together
two values:
10 + 5
TRINITYINSTITUTEOFTECHNOLOGY &RESEARCH,BHOPAL
Department of Mechanical Engineering
R divides the operators in the following groups:
• Arithmetic operators
• Assignment operators
• Comparison operators
• Logical operators Miscellaneous operators
R Arithmetic Operators
Arithmetic operators are used with numeric values to perform common mathematical operations:
+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division x/y
^ Exponent x^y
Example
my_var <- 3
my_var <<- 3
3 -> my_var
3 ->> my_var
my_var # print my_var
TRINITYINSTITUTEOFTECHNOLOGY &RESEARCH,BHOPAL
Department of Mechanical Engineering
<<- is a global assigner. You will learn more about this in the Global Variable.
R Comparison Operators
Comparison operators are used to compare two values:
== Equal x == y
!= Not equal x != y
Mechanical Engineering
EXPERIMENT-8
Categorical Variables
Categorical variables in R are stored into a factor. Let’s check the code below to convert a character variable into a factor
variable in R. Characters are not supported in machine learning algorithm, and the only way is to convert a string to an
integer.
Syntax
Arguments:
Mechanical Engineering
The values factor levels can take are fixed. For example, once you tell R that typesdata$group is a factor with two levels:
Control and Treatment, combining it with other datasets with different spellings or abbreviations for the same variable
will generate a warning.