SEE R Practical Dhara
SEE R Practical Dhara
2. MATLAB Introduction
MATLAB (matrix laboratory) is a fourth-generation high-level
programming language and interactive environment for numerical
computation, visualization and programming.
MATLAB is developed by MathWorks.
It allows matrix manipulations; plotting of functions and data;
implementation of algorithms; creation of user interfaces; interfacing
with programs written in other languages, including C, C++, Java, and
FORTRAN; analyze data; develop algorithms; and create models and
applications.
It has numerous built-in commands and math functions that help you
in mathematical calculations, generating plots, and performing
numerical methods.
MATLAB's Power of Computational Mathematics
MATLAB is used in every facet of computational mathematics.
Following are some commonly used mathematical calculations where
it is used most commonly −
• Dealing with Matrices and Arrays
• 2-D and 3-D Plotting and graphics
• Linear Algebra
• Algebraic Equations
• Non-linear Functions
• Statistics
• Data Analysis
• Calculus and Differential Equations
• Numerical Calculations
• Integration
• Transforms
• Curve Fitting
• Various other special functions
Features of MATLAB
Following are the basic features of MATLAB −
• It is a high-level language for numerical computation,
visualization and application development.
• It also provides an interactive environment for iterative
exploration, design and problem solving.
• It provides vast library of mathematical functions for linear
algebra, statistics, Fourier analysis, filtering, optimization,
numerical integration and solving ordinary differential
equations.
• It provides built-in graphics for visualizing data and tools for
creating custom plots.
• MATLAB's programming interface gives development tools for
improving code quality maintainability and maximizing
performance.
• It provides tools for building applications with custom graphical
interfaces.
• It provides functions for integrating MATLAB based algorithms
with external applications and languages such as C, Java, .NET
and Microsoft Excel.
Uses of MATLAB
MATLAB is widely used as a computational tool in science and
engineering encompassing the fields of physics, chemistry, math and
all engineering streams. It is used in a range of applications including
−
• Signal Processing and Communications
• Image and Video Processing
• Control Systems
• Test and Measurement
• Computational Finance
3. R Installation and MATLAB Installation
To install R, go to https://cloud.r-project.org/ and download the
latest version of R for Windows, Mac or Linux.
When you have downloaded and installed R, you can run R on your
computer.
The screenshot below shows how it may look like when you run R on
a Windows PC:
If you type 5 + 5, and press enter, you will see that R outputs 10.
MATLAB Installation
Local Environment Setup
Setting up MATLAB environment is a matter of few clicks. The
installer can be downloaded from here.
MathWorks provides the licensed product, a trial version and a
student version as well. You need to log into the site and wait a little
for their approval.
After downloading the installer the software can be installed through
few clicks.
Understanding the MATLAB Environment
MATLAB development IDE can be launched from the icon created on
the desktop. The main working window in MATLAB is called the
desktop. When MATLAB is started, the desktop appears in its default
layout −
+ Addition
– Subtraction
* Multiplication
/ Division
• Trigonometric functions
Trigonometric
Operation / Function
Symbol
• Exponential functions
• Square functions
Symbol Operation
^ Power or Square
• Logarithm functions
Symbol Operation
• Remainder function
Symbol Operation
Symbol Operation
Symbol Operation
Vectors:- The simplest of these objects is the vector object and there are six
data types of these atomic vectors, also termed as six classes of vectors. The
other R-Objects are built upon the atomic vectors.
Live Demo
v <- TRUE
Logical TRUE, FALSE print(class(v))
it produces the following result −
[1] "logical"
Live Demo
v <- 23.5
Numeric 12.3, 5, 999 print(class(v))
it produces the following result −
[1] "numeric"
Live Demo
v <- 2L
Integer 2L, 34L, 0L print(class(v))
it produces the following result −
[1] "integer"
Live Demo
v <- 2+5i
Complex 3 + 2i print(class(v))
it produces the following result −
[1] "complex"
Live Demo
v <- "TRUE"
Character 'a' , '"good", "TRUE", '23.4' print(class(v))
it produces the following result −
[1] "character"
Live Demo
v <- charToRaw("Hello")
Raw "Hello" is stored as 48 65 6c 6c 6f print(class(v))
it produces the following result −
[1] "raw"
When you want to create vector with more than one element, you should
use c() function which means to combine the elements into a vector.
> apple<- c("red","green","yellow")
> print(apple)
[1] "red" "green" "yellow"
> print(class(apple))
[1] "character"
# create sequence of numbers
> v <- 5:13
> print(v)
[1] 5 6 7 8 9 10 11 12 13
List:- A list is an R-object which can contain many different types of elements
inside it like vectors, functions and even another list inside it.
> list1 <- list(c(2,5,3),21.3,sin)
> print(list1)
[[1]]
[1] 2 5 3
[[2]]
[1] 21.3
[[3]]
function (x) .Primitive("sin")
$A_Matrix
[,1] [,2] [,3]
[1,] 3 5 -2
[2,] 9 1 8
> print(list_data[1])
$`1st Quarter`
[1] "Jan" "Feb" "Mar"
> print(list_data$A_Matrix)
[,1] [,2] [,3]
[1,] 3 5 -2
[2,] 9 1 8
[[2]]
[1] 2
[[3]]
[1] 3
[[4]]
[1] "Sun"
[[5]]
[1] "Mon"
[[6]]
[1] "Tue"
,,2
Factors:- Factors are the r-objects which are created using a vector. It stores the
vector along with the distinct values of the elements in the vector as labels.
The labels are always character irrespective of whether it is numeric or
character or Boolean etc. in the input vector. They are useful in statistical
modeling.
Factors are created using the factor() function. The nlevels functions gives the
count of levels.
> apple_colors <- c('green','green','yellow','red','red','red','green')
> factor_apple <- factor(apple_colors)
> print(factor_apple)
[1] green green yellow red red red green
Levels: green red yellow
> print(nlevels(factor_apple))
[1] 3
DataFrame:- Data frames are tabular data objects. Unlike a matrix in data
frame each column can contain different modes of data. The first column can
be numeric while the second column can be character and third column can be
logical. It is a list of vectors of equal length.
Data Frames are created using the data.frame() function.
> BMI <- data.frame(
+ gender = c("Male", "Male","Female"),
+ height = c(152, 171.5, 165),
+ weight = c(81,93, 78),
+ Age = c(42,38,26)
+)
> print(BMI)
gender height weight Age
1 Male 152.0 81 42
2 Male 171.5 93 38
3 Female 165.0 78 26
> str(emp.data)
'data.frame': 5 obs. of 4 variables:
$ emp_id : int 1 2 3 4 5
$ emp_name : chr "Rick" "Dan" "Michelle" "Ryan" ...
$ salary : num 623 515 611 729 843
$ start_date: Date, format: "2012-01-01" "2013-09-23" "2014-11-15" "2014-
05-11" ...
6. R Operators:-
Arithmetic Operators
Following table shows the arithmetic operators supported by R language.
The operators act on each element of the vector.
Live Demo
v <- c( 2,5.5,6)
+ Adds two vectors t <- c(8, 3, 4)
print(v+t)
it produces the following result −
[1] 10.0 8.5 10.0
Live Demo
Live Demo
v <- c( 2,5.5,6)
* Multiplies both vectors t <- c(8, 3, 4)
print(v*t)
it produces the following result −
[1] 16.0 16.5 24.0
Live Demo
v <- c( 2,5.5,6)
t <- c(8, 3, 4)
/ Divide the first vector with the second print(v/t)
When we execute the above code, it produces
the following result −
[1] 0.250000 1.833333 1.500000
Live Demo
v <- c( 2,5.5,6)
Give the remainder of the first vector
%% t <- c(8, 3, 4)
with the second print(v%%t)
it produces the following result −
[1] 2.0 2.5 2.0
Live Demo
v <- c( 2,5.5,6)
The result of division of first vector
%/% t <- c(8, 3, 4)
with second (quotient) print(v%/%t)
it produces the following result −
[1] 0 1 1
Live Demo
v <- c( 2,5.5,6)
The first vector raised to the exponent
^ t <- c(8, 3, 4)
of second vector print(v^t)
it produces the following result −
[1] 256.000 166.375 1296.000
Relational Operators
Following table shows the relational operators supported by R language. Each element of the
first vector is compared with the corresponding element of the second vector. The result of
comparison is a Boolean value.
Live Demo
Live Demo
Live Demo
Live Demo
Live Demo
Logical Operators
Following table shows the logical operators supported by R language. It is
applicable only to vectors of type logical, numeric or complex. All
numbers greater than 1 are considered as logical value TRUE.
Live Demo
It is called Element-wise Logical AND operator.
It combines each element of the first vector v <- c(3,1,TRUE,2+3i)
& with the corresponding element of the second t <- c(4,1,FALSE,2+3i)
vector and gives a output TRUE if both the print(v&t)
elements are TRUE. it produces the following result −
[1] TRUE TRUE FALSE TRUE
Live Demo
It is called Element-wise Logical OR operator. It
combines each element of the first vector with v <- c(3,0,TRUE,2+2i)
| the corresponding element of the second t <- c(4,0,FALSE,2+3i)
vector and gives a output TRUE if one the print(v|t)
elements is TRUE. it produces the following result −
[1] TRUE FALSE TRUE TRUE
Live Demo
It is called Logical NOT operator. Takes each
v <- c(3,0,TRUE,2+2i)
! element of the vector and gives the opposite
print(!v)
logical value.
it produces the following result −
[1] FALSE TRUE FALSE FALSE
The logical operator && and || considers only the first element of the
vectors and give a vector of single element as output.
Operator Description Example
Live Demo
Live Demo
Assignment Operators
These operators are used to assign values to vectors.
Live Demo
v1 <- c(3,1,TRUE,2+3i)
v2 <<- c(3,1,TRUE,2+3i)
<− v3 = c(3,1,TRUE,2+3i)
or print(v1)
= Called Left Assignment print(v2)
or print(v3)
<<− it produces the following result −
[1] 3+0i 1+0i 1+0i 2+3i
[1] 3+0i 1+0i 1+0i 2+3i
[1] 3+0i 1+0i 1+0i 2+3i
Live Demo
Miscellaneous Operators
These operators are used to for specific purpose and not general
mathematical or logical computation.
Live Demo
v1 <- 8
This operator is v2 <- 12
used to identify if t <- 1:10
%in% an element print(v1 %in% t)
belongs to a print(v2 %in% t)
vector.
it produces the following result −
[1] TRUE
[1] FALSE
Live Demo
v <- LETTERS[1:4]
for ( i in v) {
print(i)
}
[1] "A"
[1] "B"
[1] "C"
[1] "D"
v <- c("Hello","loop")
cnt <- 2
repeat {
print(v)
cnt <- cnt + 1
if(cnt > 5) {
break
}
}
[1] "Hello" "loop"
[1] "Hello" "loop"
[1] "Hello" "loop"
[1] "Hello" "loop"
8. R Conditional Statement
x <- 30L
if(is.integer(x)) {
print("X is an Integer")
}
[1] "X is an Integer"
x <- c("what","is","truth")
if("Truth" %in% x) {
print("Truth is found")
} else {
print("Truth is not found")
}
[1] "Truth is not found"
x <- c("what","is","truth")
if("Truth" %in% x) {
print("Truth is found the first time")
} else if ("truth" %in% x) {
print("truth is found the second time")
} else {
print("No truth found")
}
[1] "truth is found the second time"
9. R Matrices:-
Create a matrix taking a vector of numbers as input.
# Elements are arranged sequentially by row.
M <- matrix(c(3:14), nrow = 4, byrow = TRUE)
print(M)
# Elements are arranged sequentially by column.
N <- matrix(c(3:14), nrow = 4, byrow = FALSE)
print(N)
# Define the column and row names.
rownames = c("row1", "row2", "row3", "row4")
colnames = c("col1", "col2", "col3")
P <- matrix(c(3:14), nrow = 4, byrow = TRUE, dimnames = list(rownames,
colnames))
print(P)
[,1] [,2] [,3]
[1,] 3 4 5
[2,] 6 7 8
[3,] 9 10 11
[4,] 12 13 14
[,1] [,2] [,3]
[1,] 3 7 11
[2,] 4 8 12
[3,] 5 9 13
[4,] 6 10 14
col1 col2 col3
row1 3 4 5
row2 6 7 8
row3 9 10 11
row4 12 13 14
10.R String:-
a <- "Hello"
b <- 'How'
c <- "are you? "
print(paste(a,b,c))
print(paste(a,b,c, sep = "-"))
print(paste(a,b,c, sep = "", collapse = ""))
When we execute the above code, it produces the following result −
[1] "Hello How are you? "
[1] "Hello-How-are you? "
[1] "HelloHoware you? "
$A_Inner_list
$A_Inner_list[[1]]
[1] "green"
$A_Inner_list[[2]]
[1] 12.3
If there are missing values, then the mean function returns NA.
To drop the missing values from the calculation use na.rm = TRUE. which
means remove the NA values.
# Create a vector.
x <- c(12,7,3,4.2,18,2,54,-21,8,-5,NA)
# Find mean.
result.mean <- mean(x)
print(result.mean)
# Find mean dropping NA values.
result.mean <- mean(x,na.rm = TRUE)
print(result.mean)
13.R Functions:-
Built-in Function
Simple examples of in-built functions are seq(), mean(), max(), sum(x) and
paste(...) etc. They are directly called by user written programs. You can refer
most widely used R functions.
# Create a sequence of numbers from 32 to 44.
print(seq(32,44))
# Find mean of numbers from 25 to 82.
print(mean(25:82))
# Find sum of numbers frm 41 to 68.
print(sum(41:68))
When we execute the above code, it produces the following result −
[1] 32 33 34 35 36 37 38 39 40 41 42 43 44
[1] 53.5
[1] 1526
User-defined Function
We can create user-defined functions in R. They are specific to what a user
wants and once created they can be used like the built-in functions. Below is an
example of how a function is created and used.
# Create a function to print squares of numbers in sequence.
new.function <- function(a) {
for(i in 1:a) {
b <- i^2
print(b)
}
}
Calling a Function
# Create a function to print squares of numbers in sequence.
new.function <- function(a) {
for(i in 1:a) {
b <- i^2
print(b)
}
}
# Call the function new.function supplying 6 as an argument.
new.function(6)
When we execute the above code, it produces the following result −
[1] 1
[1] 4
[1] 9
[1] 16
[1] 25
[1] 36
3D Pie Chart
A pie chart with 3 dimensions can be drawn using additional packages. The
package plotrix has a function called pie3D() that is used for this.
# Get the library.
library(plotrix)
# Create data for the graph.
x <- c(21, 62, 10,53)
lbl <- c("London","New York","Singapore","Mumbai")
# Give the chart file a name.
png(file = "3d_pie_chart.jpg")
# Plot the chart.
pie3D(x,labels = lbl,explode = 0.1, main = "Pie Chart of Countries ")
# Save the file.
dev.off()
More than one line can be drawn on the same chart by using
the lines()function.
After the first line is plotted, the lines() function can use an additional vector as
input to draw the second line in the chart,
# Create the data for the chart.
v <- c(7,12,28,3,41)
t <- c(14,7,6,19,3)
# Give the chart file a name.
png(file = "line_chart_2_lines.jpg")
# Plot the bar chart.
plot(v,type = "o",col = "red", xlab = "Month", ylab = "Rain fall",
main = "Rain fall chart")
lines(t, type = "o", col = "blue")
# Save the file.
dev.off()