0% found this document useful (0 votes)
401 views25 pages

MATLAB MANUAL 7th SEM (ME - 705)

Uploaded by

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

MATLAB MANUAL 7th SEM (ME - 705)

Uploaded by

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

TRINITY INSTITUTE OF TECHNOLOGY &RESEARCH,BHOPAL

Department of Mechanical Engineering

LABORATORY FILE
ME705

MATLAB R PROGRAMMING

2023-24 Odd Semester

SUBMITTED BY

Abhinav Kumar
Enrollmentno: 0198ME201003
B.Tech. VII Semester

Department of Mechanical Engineering

TRINITY INSTITUTE OF TECHNOLOGY & RESEARCH

Name Enrollmentno: Collegename


1
TRINITY INSTITUTE OF TECHNOLOGY &RESEARCH,BHOPAL
Department of Mechanical Engineering

Index

S.N. Experiment/Program PageNo.


Introduction to MATLAB.
1.
Working with matrices.
2.
Rational and logical operation of MATLAB.
3.
Creating a plot using Plot function.
4.
5. 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 = [ ].
What is R Programming Language?
6.
Write R Data Types, Arithmetic & Logical Operators with Example .
7.

8. Explain Factor in R: Categorical & Continuous Variables.


9. Explain about R Data Frame: Create, Append, Select, Subset.

10. Write a program to read a string, then replace each character in the
string with its following character in ASCII code*.)

LabManual

Name Enrollmentno: Collegename


2
TRINITY INSTITUTE OF TECHNOLOGY &RESEARCH,BHOPAL
Department of Mechanical Engineering
MATLAB R PROGRAMMING

OBJECTIVES:

To teach the students basics of programs and its execution.

To teach the students the concept of MATLAB and R programmming.

To make the students learn concepts like MATLAB and R variable,data types,operators,loops etc.

To make the students understand represent concept in MATLAB and R.

To make the students understand the usage language.

To teach the student,to develop successful programs.

VISION OF THE INSTITUTE

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.

MISSION OF THE INSTITUTE

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

VISION OF THE DEPARTMENT

To spark the imagination of the MECHANICAL ENGINEERING with values,skills and creativity to solve the
real world problems.

MISSION OF THE DEPARTMENT

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.
.

Name Enrollmentno: Collegename


3
TRINITY INSTITUTE OF TECHNOLOGY &RESEARCH,BHOPAL
Department of Mechanical Engineering
INTRODUCTIONT OOP

Object oriented programming(OOP)is a computer science term used to characterize a programming


language that began development in the 1960’s. The term ‘object-oriented programming’ was originally
coined by Xerox PARC to designate a computer application that describes the methodology of using object
sas the foundation for computation.By the1980’s,OOProseto prominences’ the programming language of
choice,exemplified by the success of C++.Currently,OOPs such as Java,J2EE,C++,C=,VisualBasic.NET,Python
and java Script are popular OOP programming languages that any career-oriented Software Engineer or
developer should be familiar with.OOP is widely accepted as being far more flexible than other computer
programming languages.OOPs use three basic concepts as the fundamentals for the
Abstraction,Polymorphism,Event Handling and Encapsulation are also significant concepts within
objectoriented programming languages that are explained in online tutorial describing the functionality
of each concept in detail.

Name Enrollmentno: Collegename


4
TRINITYINSTITUTEOFTECHNOLOGY &RESEARCH,BHOPAL
Department of Mechanical Engineering

Do’s
1. Come with completed observation and record

2. Wear apron and ID card before entering into the lab.

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.

6.Write in time,out time and system details in the login register.

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.

3. Do not change system settings.

4. Do not disturb your neighbouring students.They may be busy incompleting tasks.

5. Do not remove anything from the computer laboratory without permission.


EXPERIMENT-1

AIM:- Introduction to MATLAB.

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.

Name Enrollmentno: Collegename


5
TRINITYINSTITUTEOFTECHNOLOGY &RESEARCH,BHOPAL
Department of Mechanical Engineering
In this MATLAB tutorial, we will start with the MATLAB as an environment and keep on studying with the MATLAB
programming language. We will cover entire topics of MATLAB journey; from downloading & installing of the MATLAB
environment, to its features & capabilities, to the basics programming fundamentals, and to the advance
objectorientation of the MATLAB programming language.

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

a few basic conventions:

• Separate the elements of a row with blanks or commas.

Name Enrollmentno: Collegename


6
TRINITYINSTITUTEOFTECHNOLOGY &RESEARCH,BHOPAL
Department of Mechanical Engineering
• Use a semicolon ( ; ) to indicate the end of each row.

• 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]

MATLAB displays the matrix you just entered.

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

element outside of the matrix, it is an error.

>> t = A(4,5) ??? Index exceeds matrix dimensions.


On the other hand, if you store a value in an element outside of the matrix, the

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

Name Enrollmentno: Collegename


7
TRINITYINSTITUTEOFTECHNOLOGY &RESEARCH,BHOPAL
Department of Mechanical Engineering
9 6 7 12 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

an increment. For example,

>> 100:-7:50

100 93 86 79 72 65 58 51

Subscript expressions involving colons refer to portions of a matrix.

>>A(1:k,j) is the first k elements of the jth column of A.

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

Name Enrollmentno: Collegename


8
TRINITYINSTITUTEOFTECHNOLOGY &RESEARCH,BHOPAL
Department of Mechanical Engineering
<= Less than or equal
>= Greater than or equal

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:

Name Enrollmentno: Collegename


10
TRINITYINSTITUTEOFTECHNOLOGY &RESEARCH,BHOPAL
Department of Mechanical Engineering
bitand (A, B) Bitwise AND
bitor (A, B) Bitwise OR
bitset (A, BIT) sets bit position BIT in A to 1
bitget (A, BIT) returns the value of the bit at position BIT in A
xor (A, B) Bitwise EXCLUSIVE OR

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

isnan(x) True for Not-a-Number


isinf(x) True for infinite elements
isempty(x) True for empty array.

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.

Creating a Plot Using Plot Function


The plot function has different forms, depending on the input arguments. If y is a vector, plot(y)
produces a piecewise linear graph of the elements of y versus the index of the elements of y. If you specify two vectors as
arguments, plot(x,y) produces a graph of y versus x. For example, these statements use the colon operator to create a vector of
x values ranging from zero to 2*pi, compute the sine of these values, and plot the result.

Name Enrollmentno: Collegename


11
TRINITYINSTITUTEOFTECHNOLOGY &RESEARCH,BHOPAL
Department of Mechanical Engineering

x = 0:pi/100:2*pi;
y = sin(x);
plot(y)

Now plot y variable by using:


plot(x,y)
can you see the difference at x-axis

Setting Axis Limits


By default, MATLAB finds the maxima and minima of the data to choose the axis limits to span this range. The axis command
enables you to specify your own limits axis([xmin xmax ymin ymax])

Axis Labels and Titles


The xlabel, ylabel, and zlabel commands add x-, y-, and z-axis labels. The title command adds a title at the top of the figure and
the text function inserts text anywhere in the figure.

Multiple Plots in One Figure

The subplot command enables you to display multiple plots in the same window or

print them on the same piece of paper. Typing

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

Name Enrollmentno: Collegename


12
TRINITYINSTITUTEOFTECHNOLOGY &RESEARCH,BHOPAL
Department of Mechanical Engineering

window, then the second row, and so on. For example, these statements plot data in four

different sub regions of the figure window.

t = 0:pi/10:2*pi;

x=sin(t); y=cos(t); z= 2*y-3*x; v=5-z;

subplot(2,2,1); plot(x)

subplot(2,2,2); plot(y)

subplot(2,2,3); plot(z)

subplot(2,2,4); plot(v)

Name Enrollmentno: Collegename


13
TRINITYINSTITUTEOFTECHNOLOGY &RESEARCH,BHOPAL
Department of Mechanical Engineering

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

This type of array is a row vector.


To create a matrix that has multiple rows, separate the rows with semicolons.

Name Enrollmentno: Collegename


14
TRINITYINSTITUTEOFTECHNOLOGY &RESEARCH,BHOPAL
Department of Mechanical Engineering
a = [1 3 5; 2 4 6; 7 8 10]
a = 3×3

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

0.8415 0.1411 -0.9589


0.9093 -0.7568 -0.2794
0.6570 0.9894 -0.5440
To transpose a matrix, use a single quote ('): 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)

Name Enrollmentno: Collegename


15
TRINITYINSTITUTEOFTECHNOLOGY &RESEARCH,BHOPAL
Department of Mechanical Engineering
VM = diag(M)
VM = diag(M,K)

%Data mat = rand(100);


%Coordinates x_coord =
round(rand(10,1)*100); y_coord
= round(rand(10,1)*100);
%Extract coordinates
extracted_coord = diag(mat(x_coord,y_coord))

Name Enrollmentno: Collegename


16
TRINITYINSTITUTEOFTECHNOLOGY &RESEARCH,BHOPAL
Department of Mechanical Engineering

EXPERIMENT-6

Aim:-To perform the function oriented diagram

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.

Features of R Programming Language Statistical


Features of R:

• 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.

Level 1-TheLevel 0DFD isbrokendowninto morespecific,Level1DFD.Level


1DFDdepicts basicmodules
inthesystemandflowofdataamongvariousmodules. Level 1 DFD also mentions
basic processes and sources ofinformation.
TRINITYINSTITUTEOFTECHNOLOGY &RESEARCH,BHOPAL
Department of Mechanical Engineering
.
TRINITYINSTITUTEOFTECHNOLOGY &RESEARCH,BHOPAL
Department of Mechanical Engineering

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:

Basic Data Types


Basic data types in R can be divided into the following types:

• numeric - (10.5, 55, 787)


• integer - (1L, 55L, 100L, where the letter "L" declares this as an integer)
• complex - (9 + 3i, where "i" is the imaginary part)
• character (a.k.a. string) - ("k", "R is exciting", "FALSE", "11.5")
• logical (a.k.a. boolean) - (TRUE or FALSE)

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:

Operator Name Example

+ Addition x+y

- Subtraction x-y

* Multiplication x*y

/ Division x/y

^ Exponent x^y

%% Modulus (Remainder from division) x %% y

%/% Integer Division 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.

It is also possible to turn the direction of the assignment operator.

x <- 3 is equal to 3 -> x

R Comparison Operators
Comparison operators are used to compare two values:

Operator Name Example

== Equal x == y

!= Not equal x != y

> Greater than x>y

< Less than x<y

>= Greater than or equal to x >= y

<= Less than or equal to x <= y


TRINITYINSTITUTEOFTECHNOLOGY &RESEARCH,BHOPAL
Department of

Mechanical Engineering

EXPERIMENT-8

AIM:- Explain Factor in R: Categorical & Continuous Variables.


Factor in R is a variable used to categorize and store the data, having a limited number of different values. It stores the
data as a vector of integer values. Factor in R is also known as a categorical variable that stores both string and integer
data values as levels. Factor is mostly used in Statistical Modeling and exploratory data analysis with R.

Categorical and continuous


• In descriptive statistics for categorical variables in R, the value is limited and usually based on a particular finite
group. For example, a categorical variable in R can be countries, year, gender, occupation.
• A continuous variable, however, can take any values, from integer to decimal. For example, we can have the
revenue, price of a share, etc..

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

factor(x = character(), levels, labels = levels, ordered = is.ordered(x))

Arguments:

• x: A vector of categorical data in R. Need to be a string or integer, not decimal.


• Levels: A vector of possible values taken by x. This argument is optional. The default value is the unique list of
items of the vector x.
• Labels: Add a label to the x categorical data in R. For example, 1 can take the label `male` while 0, the label
`female`.
• ordered: Determine if the levels should be ordered in categorical data in R.
TRINITYINSTITUTEOFTECHNOLOGY &RESEARCH,BHOPAL
Department of

Mechanical Engineering

Factor variables (categorical)


Factors are fussy characters. Factors are fussy because they include something called levels. Levels are all the unique
values a factor variable could take, e.g., like when we looked at typesdata %>% count(group). Using factors rather than
just characters can be useful because:

 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.

current_datetime <- Sys.time() current_datetime

## [1] "2023-09-15 11:56:12 GMT"


TRINITYINSTITUTEOFTECHNOLOGY &RESEARCH,BHOPAL
Department of

You might also like