0% found this document useful (0 votes)
33 views

Matlab Introduction: C. Jairaj Department of Electronics Engineering, KIT's COE, Kolhapur

The document provides an introduction to Matlab. It discusses that Matlab is a program for numerical computation designed for solving problems using matrices. It then covers various Matlab elements like data types, variables, matrices, and arrays. It explains how to initialize variables using assignment statements and built-in functions. It also discusses key concepts like multidimensional arrays, subarrays, and special Matlab variables.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views

Matlab Introduction: C. Jairaj Department of Electronics Engineering, KIT's COE, Kolhapur

The document provides an introduction to Matlab. It discusses that Matlab is a program for numerical computation designed for solving problems using matrices. It then covers various Matlab elements like data types, variables, matrices, and arrays. It explains how to initialize variables using assignment statements and built-in functions. It also discusses key concepts like multidimensional arrays, subarrays, and special Matlab variables.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 46

Matlab Introduction

C. Jairaj
Department of Electronics Engineering,
KIT’s COE, Kolhapur
[email protected]

4/28/2019 KIT'S COEK 1


Matlab Basic
• Matlab introduction
• Matlab elements
– Types
– Variables
– Matrices
• Loading, saving and ploting
• Matlab Programming language
• Scripts and functions
4/28/2019 KIT'S COEK 2
Matlab Introduction
• Matlab: Program for numerical computation.
• Designed for solving linear algebra type
problems using matrices.
• Stands for MATrix LABoratory.
• Why it is useful for prototyping AlI projects:
– large toolbox of numeric/image library functions
– very useful for displaying, visualizing data
– high-level: focus on algorithm structure, not on
lowlevel details
– allows quick prototype development of algorithms

4/28/2019 KIT'S COEK 3


Introduction contd…1
• Some other aspects of Matlab
– Matlab is an interpreter -> not as fast as compiled
code
• Typically quite fast for an interpreted language
• Often used early in development -> can then convert to
C (e.g.,) for speed
– Can be linked to C/C++, JAVA, SQL, etc
– Commercial product, but widely used in industry
and academia
– Many algorithms and toolboxes freely available

4/28/2019 KIT'S COEK 4


Getting Started

Editor Window
Workspace
and current
directory
Command
Command Window
History
4/28/2019 KIT'S COEK 5
Getting Started

4/28/2019 KIT'S COEK 6


Matlab Elements: Data Types

4/28/2019 KIT'S COEK 7


Matlab Elements: Variables
Variables and Arrays
• Array: A collection of data values organized into rows and
columns, and known by a single name.

Row 1

Row 2

Row 3
arr(3,2)
Row 4

Col 1 Col 2 Col 3 Col 4 Col 5

4/28/2019 KIT'S COEK 8


Arrays
• The fundamental unit of data in MATLAB
• Scalars are also treated as arrays by MATLAB
(1 row and 1 column).
• Row and column indices of an array start from
1.
• Arrays can be classified as vectors and
matrices.

4/28/2019 KIT'S COEK 9


• Vector: Array with one dimension

• Matrix: Array with more than one dimension

• Size of an array is specified by the number of


rows and the number of columns, with the
number of rows mentioned first (For example: n
x m array).
Total number of elements in an array is the
product of the number of rows and the number
of columns.
4/28/2019 KIT'S COEK 10
1 2
a= 3 4 3x2 matrix  6 elements
5 6

b=[1 2 3 4] 1x4 array  4 elements, row vector

1
c= 3 3x1 array  3 elements, column vector
5

a(2,1)= b(3)= c(2)=

Row # Column #

4/28/2019 KIT'S COEK 11


Variables contd…1
• Have not to be previously declared
• Variable names can contain up to 63 characters
• Variable names must start with letter followed by
letters, digits, and underscores.
• Contents can be used or modified at any time.
• case sensitive
• Give meaningful (descriptive and easy-to-
remember) names for the variables. Never define
a variable with the same name as a MATLAB
function or command

4/28/2019 KIT'S COEK 12


Types of Matlab Variable
Common types of MATLAB variables
• double: 64-bit double-precision floating-point numbers
– can hold real, imaginary or complex numbers in the range
from ±10-308 to ±10308 with 15 or 16 decimal digits.
ex: >> var = 1 + i ;
• char: 16-bit values, each representing a single char
– used to hold character strings.
ex: >> comment = ‘This is a character string’ ;

The type of data assigned to a variable determines the


type of variable that is created.

4/28/2019 KIT'S COEK 13


Variables contd…3
• Initializing Variables in Assignment Statements
An assignment statement has the general form
var = expression
• Examples:
• >> var = 40 * i; >> a2 = [0 1+8];
• >> var2 = var / 5; >> b2 = [a2(2) 7 a];
• >> array = [1 2 3 4]; >> c2(2,3) = 5;
• >> x = 1; y = 2; >> d2 = [1 2];
• >> a = [3.4]; >> d2(4) = 4;
• >> b = [1.0 2.0 3.0 4.0];
• >> c = [1.0; 2.0; 3.0];
• >> d = [1, 2, 3; 4, 5, 6]; ‘;’ semicolon suppresses the
• >> e = [1, 2, 3 automatic echoing of values but
• 4, 5, 6]; it slows down the execution.

KIT'S COEK
4/28/2019 14
Variables contd…4
Initializing Variables in Assignment Statements
• Arrays are constructed using brackets and
semicolons. All of the elements of an array are listed
in row order.
• The values in each row are listed from left to right
and they are separated by blank spaces or commas.
• The rows are separated by semicolons or new lines.
• The number of elements in every row of an array
must be the same.
• The expressions used to initialize arrays can include
algebraic operations and all or portions of previously
defined arrays.
KIT'S COEK
4/28/2019 15
Variables contd…5

Initializing with Built-in Functions


• zeros(n) >> a = zeros(2);
• zeros(n,m) >> b = zeros(2, 3);
• zeros(size(arr)) >> c = [1, 2; 3, 4];
• ones(n) >> d = zeros(size(c));
• ones(n,m)
• ones(size(arr))
• eye(n)
• eye(n,m)

• length(arr)
• size(arr)
4/28/2019 KIT'S COEK 16
Arrays

Multidimensional Arrays
• A two dimensional array with m rows and n columns will
occupy mxn successive locations in the computer’s memory.
• MATLAB always allocates array elements in column major
order.
1
a= [1 2 3; 4 5 6; 7 8 9; 10 11 12]; 4
a(5) = a(1,2) = 2 1 2 3 7
4 5 6 10
• A 2x3x2 array of three dimensions 7 8 9 2
c(:, :, 1) = [1 2 3; 4 5 6 ]; 10 11 12 5
c(:, :, 2) = [7 8 9; 10 11 12]; 8
11

4/28/2019 KIT'S COEK 17


Arrays contd…1
Subarrays
• It is possible to select and use subsets of MATLAB arrays.
arr1 = [1.1 -2.2 3.3 -4.4 5.5];
arr1(3) is 3.3
arr1([1 4]) is the array [1.1 -4.4]
arr1(1 : 2 : 5) is the array [1.1 3.3 5.5] Indicates the interval

• For two-dimensional arrays, a colon can be used in a subscript


to select all of the values of that subscript.
arr2 = [1 2 3; -2 -3 -4; 3 4 5];
arr2(1, :)
arr2(:, 1:2:3)

4/28/2019 KIT'S COEK 18


Arrays contd…2

Subarrays
• The end function: When used in an array subscript, it returns
the highest value taken on by that subscript.
arr3 = [1 2 3 4 5 6 7 8];
arr3(5:end) is the array [5 6 7 8]
arr4 = [1 2 3 4; 5 6 7 8; 9 10 11 12];
arr4(2:end, 2:end)
• Using subarrays on the left hand-side of an assignment
statement:
arr4(1:2, [1 4]) = [20 21; 22 23];
(1,1) (1,4) (2,1) and (2,4) are updated.
arr4 = [20 21; 22 23]; all of the array is changed.
4/28/2019 KIT'S COEK 19
Arrays contd…3

Subarrays
• Assigning a Scalar to a Subarray: A scalar value on the right-
hand side of an assignment statement is copied into every
element specified on the left-hand side.
>> arr4 = [1 2 3 4; 5 6 7 8; 9 10 11 12];
>> arr4(1:2, 1:2) = 1
arr4 =
?
1 1 3 4
1 1 7 8
9 10 11 12

4/28/2019 KIT'S COEK 20


Variables contd…2
• Some special variables in Matlab
Name Description
ans Default variable name for results
Pi Value of ‘p’
eps Smallest incremental number
inf Infinity
NaN Not a number viz. ‘0/0’
realmin The smallest usable positive real number
realmax The largest usable positive real number
current date and time in the form of a 6-element
clock row vector containing the year, month, day, hour,
minute, and second
i, j
1
4/28/2019 KIT'S COEK 21
Data types

Changing the data format


>> value = 12.345678901234567;
format short  12.3457
format long  12.34567890123457
format short e  1.2346e+001
format long e  1.234567890123457e+001
format short g  12.346
format long g  12.3456789012346
format rat  1000/81

4/28/2019 KIT'S COEK 22


display

The disp( array ) function


>> disp( 'Hello' )
Hello
>> disp(5)
5
>> disp( [ ‘KIT ' ‘MATLAB' ] )
KIT MATLAB
>> name = ‘xyz';
>> disp( [ 'Hello ' name ] )
Hello xyz

4/28/2019 KIT'S COEK 23


The num2str() and int2str() functions
>> d = [ num2str(21) '-July-' num2str(2012) ];
>> disp(d)
21-July-2012
>> x = 23.11;
>> disp( [ 'answer = ' num2str(x) ] )
answer = 23.11
>> disp( [ 'answer = ' int2str(x) ] )
answer = 23

4/28/2019 KIT'S COEK 24


fprintf

The fprintf( format, data ) function


– %d integer
– %f floating point format
– %e exponential format
– %g either floating point or exponential
format, whichever is shorter
– \n new line character
– \t tab character

4/28/2019 KIT'S COEK 25


fprintf contd…
>> fprintf( 'Result is %d', 3 )
Result is 3
>> fprintf( 'Area of a circle with radius %d is %f', 3, pi*3^2 )
Area of a circle with radius 3 is 28.274334
>> x = 5;
>> fprintf( 'x = %3d', x )
x= 5
>> x = pi;
>> fprintf( 'x = %0.2f', x )
x = 3.14
>> fprintf( 'x = %6.2f', x )
x = 3.14
>> fprintf( 'x = %d\ny = %d\n', 3, 13 )
x=3
y = 13
4/28/2019 KIT'S COEK 26
Built-in Functions
Built-in MATLAB Functions
• result = function_name( input );
– abs, sign
– log, log10, log2
– exp
– sqrt
– sin, cos, tan, asin, acos, atan
– max, min
– round, floor, ceil, fix
– mod, rem
• help elfun  help for elementary math
4/28/2019
functions KIT'S COEK 27
Errorrrrrrrrrrrrr
Types of errors in MATLAB programs
• Syntax errors
– Check spelling and punctuation
• Run-time errors
– Check input data
– Can remove “;” or add “disp” statements
• Logical errors
– Use shorter statements
– Check types
– Check units
– Ask your friends, assistants, instructor, …

4/28/2019 KIT'S COEK 28


Command Summary

Summary
• help command  Online help
• lookfor keyword  Lists related commands
• which  Version and location info
• clear  Clears the workspace
• clc  Clears the command window
• diary filename  Sends output to file
• diary on/off  Turns diary on/off
• who, whos  Lists content of the workspace
• more on/off  Enables/disables paged output
• Ctrl+c  Aborts operation
• …  Continuation
• %  Comments

4/28/2019 KIT'S COEK 29


Matlab Assignment and Operators
type notation Example description

Assignment = a=b a assigned the value of b


Adding + a+b a added with b
Subtraction - a–b b subtracted from a
* a*b a multiplied by b
Multiplication
.* a .* b Vector a multiplied by vector b
/ a/b a divided by b
Division
./ a ./ b Vector a divided by vector b
^ a^b a to the power b
Power
.^ a .^ b

4/28/2019 KIT'S COEK 30


Relational operators
• Provides 6 relational operators
Type Description

< Less than

<= Less than or equal to

> Greater than

>= Greater than or equal to

== Equal to

~= Not equal to

4/28/2019 KIT'S COEK 31


Logical operators
• Provides 3 logical operators
precedence
Type Description
And
& Equal precedence with
or
Or
I Equal precedence with
and
not
~ Highest precedence
4/28/2019 KIT'S COEK 32
Logical Functions

4/28/2019 KIT'S COEK 33


Matlab Matrices
• Matlab treats all variables as matrices.
• Matrix can be thought of as an array
• Vectors are special forms of matrices and contain only
one row OR one column.
• Scalars are matrices with only one row AND
• one column
• Matrix with only one row is called a row vector. E.g.
– rowvec = [12 , 14 , 63]
• Matrix with only one column is called column vector.
E.g.
– colvec = [12; 14; 63]
• A matrix can be created in Matlab as follows
– row_col = [1 2 3; 4 5 6; 7 8 9]

4/28/2019 KIT'S COEK 34


Matrix contd…1
• Extracting a Sub-Matrix
– A portion of a matrix can be extracted and stored
in a smaller matrix by specifying the names of
both matrices and the rows and columns to
extract. The syntax is:
• sub_matrix = matrix ( r1 : r2 , c1 : c2 ) ;
• r1 and r2 specify the beginning and ending
rows and c1 and c2 specify the beginning and
ending columns to be extracted to make the
new matrix.

4/28/2019 KIT'S COEK 35


Extracting sub-matrix

4/28/2019 KIT'S COEK 36


Extracting sub-matrix

4/28/2019 KIT'S COEK 37


Matrix functions in Matlab
• X = ones(r,c) % Creates matrix full with ones
• X = zeros(r,c) % Creates matrix full with zeros
• A = diag(x) % Creates squared matrix with
vector x in diagonal
• [r,c] = size(A) % Return dimensions of mat. A
• +-*/ % Standard operations
• .+ .- .* ./ % Wise addition, subtraction,…
• v = sum(A) % Vector with sum of columns
4/28/2019 KIT'S COEK 38
Matrix functions in Matlab
• X = A’ % Transposed matrix
• X = inv(A) % Inv. matrix sqrd matrix
• X = pinv(A) % Pseudo inverse
• X = chol(A) % Cholesky decomp.
• d = det(A) % Determinant
• [X,D] = eig(A) % Eigenvalues and eigenvectors
• [Q,R] = qr(X) % QR decomposition
• [U,D,V] = svd(A) % singular value decomp.

4/28/2019 KIT'S COEK 39


Plot
• Lots of function for plotting data.
• The basic one will plot one vector vs. another.
– The first one will be treated as the abscissa (or x)
vector and
– The second as the ordinate (or y) vector.
• >> plot (time, dist) % plotting versus time
• Also plot a vector vs. its own index.
– Index treated as the abscissa
• >> plot (dist) % plotting versus index

4/28/2019 KIT'S COEK 40


Plot 1

4/28/2019 KIT'S COEK 41


Plot 2

4/28/2019 KIT'S COEK 42


Plot 3
• Putting axis labels, titles, legends

4/28/2019 KIT'S COEK 43


4/28/2019 KIT'S COEK 44
THE END
4/28/2019 KIT'S COEK 45
4/28/2019 KIT'S COEK 46

You might also like