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

Matlab Sck Ppt

This document serves as an introductory guide to MATLAB, covering its features, desktop environment, and basic commands for computation and visualization. It includes sections on operators, arrays, strings, graphs, flow control statements, and function files, providing essential information for users to get started with MATLAB. The document also discusses file types, data manipulation, and plotting simple graphs, making it a comprehensive resource for beginners.

Uploaded by

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

Matlab Sck Ppt

This document serves as an introductory guide to MATLAB, covering its features, desktop environment, and basic commands for computation and visualization. It includes sections on operators, arrays, strings, graphs, flow control statements, and function files, providing essential information for users to get started with MATLAB. The document also discusses file types, data manipulation, and plotting simple graphs, making it a comprehensive resource for beginners.

Uploaded by

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

MATLAB – Getting Started

Dr. Kulkarni Samadhan C.


Dept. of E&TC
GCOE, Jalgaon
Outline
 Introduction
 MATLAB desktop
 On line help
 General purpose commands
 Operators
 Output formats
 Arrays and Matrices
 Strings
 Graphs
 Flow Control Statements
 Function files
Introduction
 Software package for high performance
computation and visualization.
 Provides an interactive environment with built in
functions, graphics and animation.
 The name MATLAB stands for MATrix
LABoratory
 Widely used as a platform for developing
prototypes in various research areas.
 Can be linked with C/C++, Java, SQL.
 MATLAB is an interpreter-
interpreter- not fast as compiled
code.
MATLAB desktop
 Command Window
– type commands
 Current Directory
– View folders and m- m-files
 Workspace
– View program variables
– Double click on a variable
to see it in the Array
Editor
Command History
– view past commands
– save a whole session
using diary
Other MATLAB Windows
 Figure Window:
Window: The output of all graphics
commands are flushed to graphics or figure
window.
 The user can create as many as figure windows
by using keyword ‘figure’ as the system
memory will allow.
 Editor Window:
Window: In the editor window, we can
write, edit and save our own program files
called as ‘m files’
On line help
 Extensive and powerful on line help is one of the
key pillars of MATLAB that makes it more user
friendly.
 On line documentation:
documentation: MATLAB provides on line
help for all its built-
built-in functions and programming
language constructs. The commands lookfor, help,
helpwin and helpdesk provide online help.
 Demo
Demo:: MATLAB has a demonstration program that
shows many of its features. Type demo at the
MATLAB prompt to invoke the demonstration and
follow the instructions
General Purpose Commands
General Info. On line Help
1.computer 1. help
2.clock 2. helpwin
3.date 3. helpdesk
4.ver 4. help topic
5.More 5. lookfor string
6.bench 6. demo
General Purpose Commands
Workspace Information
1.who Lists all the variables in workspace

2.whos Lists all the variables in workspace


with their size
3. clc Clears the command window and
command history
4. what Lists m files and mat files on the disk

5. Clear all Clears all variables and functions from


work space
6. Clear x, y, z Clears variables x,y and z
7. clf Clears the figure window
General Purpose Commands
Directory Information Termination
1.pwd 1.^c (control
(control- -c)
2.cd Aborts the current
command execution
3.dir
4.copyfile
5.makedirectory
6.ls (same
(same as dir)
dir)
MATLAB Files: Overview
There are 2 types of .m files
 Scripts: These files don't accept
input arguments or return output
arguments. These files work only on
data in workspace.
 Functions: These files accept input
arguments and return output
arguments. Always start with
keyword function. (To be studied in
detail in later sessions.)
Script Files
 Script file is set of commands which are
executed in sequence.
 Written in MATLAB editor window.
 Can be created from command line

edit filename.m
(eg. edit script_demo.m)
or click
Operators (arithmetic)
+addition
.* element-by
element-by--
- subtraction element mult
* multiplication ./ element-
element-by
by--
/ division element div
^power .^ element-
element-by
by--
element power
‘ transpose
Operators (Relational, logical)
== equal
~= not equal
< less than
<= less than or equal
> greater than
>= greater than or equal

& AND
| OR
~ NOT
Output Format
 format short 31.4159
 format short e 3.1416e+001
 format long 31.41592653589793
 format long e 3.141592653589793e+001
 format short g 31.416
 format long g 31.4159265358979
 format hex 403f6a7a2955385e
 format rat 3550/113
 format bank 31.42
Note: The default format is short
The format type is set by typing format type on the
command line.
Variables
 Variable names must begin with a letter,
followed by any combination of letters,
numbers and the underscore (_) character.
character.
 The MATLAB language is Case Sensitive.
NAME, name and Name are all different
variables..
variables
 Never define a variable with the same
name as a MATLAB function or command.
MATLAB Special Variables
ans Default variable name for results
pi Value of 
eps Smallest incremental number
inf Infinity
NaN Not a number e.g. 0/0
i and j i = j = square root of -1
realmin The smallest usable positive real
number
realmax The largest usable positive real
number
Arrays
 The fundamental unit of data in MATLAB
 Scalars are also treated as arrays by
MATLAB (1 row and 1 column).
column).
 Row and column indices of an array start
from 1.
 Arrays can be classified as vectors and
matrices..
matrices
Arrays (contd.)
 Vector: Array with one dimension

 Matrix: Array with more than one dimension

 Size of an array is specified by the number


number of rows
and the number
number of columns,
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.
columns.
 Matrix dimensions can be obtained by size
function.. For vector,
function vector, length function can be used.
used.
Array Initialization
Arrays are constructed using brackets and
semicolons..
semicolons
e.g. X=[
X=[11 2 3; 4 5 6]
 The rows are separated by semicolons or
new lines
lines..
 The number of elements in every row of
an array must be the same
same..
 Matrix is entered row wise
Initialization (contd.)
 Initializing with Shortcut Expressions
[first element : increment: last element]
(default increment is 1)
 Colon operator: a shortcut notation used
to initialize arrays with thousands of
elements
>> x = 1 : 2 : 10;
10;
>> angles = (0.01 : 0.01 : 1) * pi
pi;;
Initializing with built in functions
 zeros (n)
 zeros (m , n)
 ones (n)
 ones(m , n)
 rand(n)
 eye (n)
 linspace (a, b, n)
 logspace (a, b, n)
 x=[]; empty matrix initialization
Initializing with keyboard input
 The input function displays a prompt
string in the Command window and then
waits for the user to respond.

my_val = input( ‘Enter an input value: ’ );

in1 = input( ‘Enter data: ’ );


in2 = input( ‘Enter data: ’ ,`s`);
Array Indexing or subscripting
 Elements are accessed by specifying their row and column
indices.. A( i , j) refers to element aij of matrix A.
indices
 MATLAB allows a range of rows and columns to be
specified at the same time.time.
 e.g. x=A(m
x=A(m::n, k:l) , It specifies mth row to nth row and kth
column to lth columncolumn.. This specified subsub--matrix of A is
assigned to x.
 When all rows (or columns) of a particular matrix are to be
handled, a colon (:) operator can be used as a row (or
column) index
index..
e.g. y=A(
y=A(1 1:5,:), It specifies that all columns of first to fifth row
of A are assigned to y.
Matrix Manipulations
 It includes extracting any part or subsub--
matrix, delete or add rows or columns
columns..
 By specifying, row and column indices of
matrix , one can reference and modify any
sub--matrix of matrix
sub matrix..
e.g. A = 4x4 matrix
matrix;; B=
B=2
2x4 matrix, we can
write A(
A(33:4,:)=B

Note: In such manipulations, it is


Note:
imperative that sizes of sub-
sub-matrices to be
manipulated are compatible
Matrix Manipulations
 Reshaping the matrices: Matrices can be
reshaped into a vector or any other appropriately
size matrix.
 As a vector: b=A(:), (matrix A is stacked into
vector b column wise)
 As a differently sized matrix: If matrix A is an m x n
matrix, it can be reshaped into a p x q matrix, as
long as m x n = p x q
e.g.. y=reshape(A, p, q)
e.g
Matrix Manipulations
 Appending a row or column:
A=[A u] ; appends the column vector u to the columns
of A
A=[A; v];
v]; appends the row vector v to the rows of A
 Concatenation:
B=cat(1,A,B) concatenating two matrices row wise
(similar to [A;B]
[A;B]))
B=cat(2,A,B) concatenating two matrices column wise
(similar to [A B])
B])
 Any row or column of a matrix can be deleted by
assigning the row or column to a null vector.
e.g. A(2,:)=[] deletes second row of matrix A
More Functions on Matrix Manipulation
Function Description
1. rot90 rotates a matrix by 900
2. fliplr flips a matrix from left to right
3. flipud flips a matrix from up to down
4. tril extracts a lower triangular part of matrix
5. triu extracts a lower triangular part of matrix
6. fix rounds a matrix elements towards 0
7. ceil rounds a matrix elements towards infinity
8. floor rounds a matrix elements towards minus infinity
9. find finds indices of non-zero elements of matrix
10. I=find(expr) finds indices of elements for which expression value is true
11. det Gives the determinant of matrix
12. eig returns a vector containing eigenvalues of a square matrix
Strings
 All character strings are entered within 2
single quotes. – ‘string
string’’
 MATLAB treats every string as a row vector
with one element per character.
 Hence to create a column vector of text
objects, each text string must have exactly
same no. of characters.
 Text strings of different lengths can be made
of equal length by padding them with blanks.
 An easier way of doing this thing is to use a
command char
e.g. str=char(‘hi’, ‘hello’, ‘namaste’)
String Manipulations
Built in functions for character string manipulations
Function Description
Char Creates character arrays using automatic padding
abs converts characters to their ASCII numeric values
int2str converts integers to string
num2str converts numbers to string
findstr Finds a specified substring in a given string
mat2str Converts a matrix to string
lower converts uppercase letters in a string to lowercase
upper converts lowercase letters in a string to uppercase
strcmp Compares two strings, returns 1 if same
strncmp Compares the first n characters in given string
strcat concatenates strings horizontally, ignoring trailing blanks
strvcat concatenates strings horizontally, ignoring empty strings
Displaying the Data
 The disp( array ) function
– >> disp( 'Hello' )
– Hello
– >> disp(5)
– 5
– >> disp( [ 'Bilkent ' 'University' ] )
– Bilkent University

– >> name = 'Alper


'Alper';';
– >> disp( [ 'Hello ' name ] )
– Hello Alper
Displaying the data
 The fprintf( format
format,, data ) function writes
data to the file in a given format.
– %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
Saving into and loading from
binary Mat-
Mat-files
 Data files
• save filename var1 var2 …
– >> save myfile.mat x y  binary
– >> save myfile.dat
myfile.dat x –ascii  ascii
• load filename
– >> load myfile.mat  binary
– >> load myfile.dat –ascii  ascii
Plotting Simple Graphs
Function Description
Plot(x, y) plots vector y versus vector x
stem(x, y) plots the data sequence Y as stems from the x
axis versus vector y
subplot(m, n, p) breaks the figure window into m x n matrix
P denotes current plot
title (‘string’) adds text at the top of the current axis.
xlabel(‘string’) adds text beside the X-axis on the current axis.
ylabel(‘string’) adds text beside the Y-axis on the current axis.
grid on adds major grid lines to the current axes.
text (x, y, ‘string’) adds the text in the quotes to location (X,Y)
gtext(‘string’) displays the graph window, puts up a
cross-hair, and waits for a mouse button or
keyboard key to be pressed.
Logic Control
 It provides a logical branching for computations.
 It works on Conditional statements
– IF / ELSEIF / ELSE
– SWITCH / CASE / OTHERWISE

e.g. if I == J
A(I,J) = 2;
elseif abs(I-
abs(I-J) == 1
A(I,J) = -1;
else
A(I,J) = 0;
end
Logic Control
(Switch Case and Otherwise)
More efficient than elseif statements
Only the first matching case is executed
color = input(‘color =’,’s’);
switch color
case ‘red’
c=[1 0 0]
case ‘green’
c=[0 1 0]
case ‘blue’
c=[0 0 1];
otherwise
disp (‘invalid choice of color’);
end
Iterative loops (For loop)
Similar to other N=10;
programming for I = 1:N
languages for J = 1:N

statement1
statement2
Repeats loop a set
number of times statement3
(based on index)
end
end
Can be nested
Iterative loops (while loop)
Similar to other % let us find all powers of 2
programming below 1000
languages v=[ ]; num=1; i=1;
while num < 1000
i=i+1;
Repeats loop until num=2^i;
logical condition v=[v num]
returns FALSE. end
v % display all powers of 2
below 1000
Can be nested.
Break, error, return
 The command break inside a for or while loop
terminates the loop, even if the condition for execution is
true.
 If the loops are nested then break terminates only the
innermost loop.
 The command error(‘message’) inside a function or
script aborts the execution, displays the error message
and returns the control to keyboard.
 The command return simply returns the control to
invoking function.
Function Files
 A function file is also an m-
m-file except that variables
are local.
 These are like that of functions in C.
 A function file begins with a function definition line.
function [ output variables]=function_name(input
variables);
 The function name must be the same as the file
name (without .m extension)
 The first word in the function definition line, function,
must be a lowercase. A common mistake is to type
as Function.

You might also like