Sie sind auf Seite 1von 44

S.

NISHARANI,
Assistant Professor/ECE,
Kamaraj College of Engineering and Technology,
Madurai
 MATLAB represents MATrix LABoratory
 A numerical analyst called Cleve Moler wrote the first version
of Matlab in the 1970s.
 MATLAB -a high-performance language for technical
computing.
 It integrates computation, visualization, and programming
environment.

Kamaraj College of Engineering and


Technology 4/2/2019
Major tools available in the desktop are
 The Command Window
 The Command History
 The Workspace
 The Current Directory
 The Help Browser
 The Start button

Kamaraj College of Engineering and


Technology 4/2/2019
Kamaraj College of Engineering and
Technology 4/2/2019
Kamaraj College of Engineering and
Technology 4/2/2019
 Issuing the command
>> diary mysession
 Text that appears on the screen would be saved to the
file mysession located in the directory
 The record may be terminated by
>> diary off

Kamaraj College of Engineering and


Technology 4/2/2019
 helpdesk – starts the MATLAB interactive help browser
 help commandname – displays documentation for
function/command name.
 help ops will list the Matlab operators.
 lookfor string – searches all help files for ‘string’ in the
description (first comment line), and displays the function
names with the description.

Kamaraj College of Engineering and


Technology 4/2/2019
• just type the expression you want to evaluate
>> 1+2*3
ans =
7
• >> x = 1+2*3
• x=
• 7

Kamaraj College of Engineering and


Technology 4/2/2019
 Variable names are case sensitive.
 The length of variable name can be known by namelengthmax
command.
 Variable names can contain up to 63 characters (as of MATLAB
2014a and newer).
 Variable names must start with a letter followed by letters, digits,
and underscores.
 Variable names should not duplicate the Matlab key words.

Kamaraj College of Engineering and


Technology 4/2/2019
 variable name = a value (or an expression)
For example,
>> x = expression
 expression can involve:
manual entry
built-in functions
user-defined functions

Kamaraj College of Engineering and


Technology 4/2/2019
 Row vector
 lists of numbers separated by either commas or spaces.
>> v = [ 1 3, sqrt(5)]
v = 1.0000 3.0000 2.2361
>> length(v)
ans = 3
 Column vector
>> c = [ 1; 3; sqrt(5)]
c = 1.0000
3.0000 The size of the vector can be
2.2361 found by the command
>> c2 = [3 4 5] length().
c2 =
3
4
5
Kamaraj College of Engineering and
Technology 4/2/2019
 MATLAB treats all variables as matrices. For our purposes a matrix
can be thought of as an array, in fact, that is how it is stored.

 Vectors are special forms of matrices and contain only one row OR
one column.

 Scalars are matrices with only one row AND one column

Kamaraj College of Engineering and


Technology 4/2/2019
 A matrix can be created in MATLAB as follows (note the commas
AND semicolons):

EDU» matrix = [1 , 2 , 3 ; 4 , 5 ,6 ; 7 , 8 , 9]

matrix =
1 2 3
4 5 6
7 8 9
 The size of the matrix can be found by the command size().

Kamaraj College of Engineering and


Technology 4/2/2019
 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 ) ;

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

Kamaraj College of Engineering and


Technology 4/2/2019
 A column vector can be
extracted from a matrix. As an  Here we extract column 2 of
example we create a matrix the matrix and make a column
below: vector:

EDU» matrix=[1,2,3;4,5,6;7,8,9]
EDU» col_two=matrix( : , 2)
matrix =
col_two =
1 2 3
2
4 5 6
5
7 8 9 8

Kamaraj College of Engineering and


Technology 4/2/2019
 A row vector can be extracted
 Here we extract row 2 of the
from a matrix. As an example
matrix and make a row vector.
we create a matrix below:
Note that the 2:2 specifies the
second row and the 1:3
EDU» matrix=[1,2,3;4,5,6;7,8,9] specifies which columns of the
row.
matrix =
EDU» rowvec=matrix(2 : 2 , 1 : 3)
1 2 3
4 5 6 rowvec =
7 8 9
4 5 6

Kamaraj College of Engineering and


Technology 4/2/2019
 zeros – create a matrix of zeros
 ones – create a matrix of ones
 rand – create a matrix of random numbers
 eye – create an identity matrix

Kamaraj College of Engineering and


Technology 4/2/2019
>> A = [1 1 1; 2 2 2; 3 3 3];
>> B = ones(3,3);
>> A*B
ans =
333
666
999
>> A.*B
ans =
111
222
333

Kamaraj College of Engineering and


Technology 4/2/2019
A’ – transpose of matrix A. Also transpose(A).
det(A) – determinant of A
eig(A) – eigenvalues and eigenvectors
inv(A) – inverse of A
svd(A) – singular value decomposition
norm(A) – matrix or vector norm
find(A) – find indices of elements that are nonzero. Can also
pass an expression to this function, e.g. find(A > 1) finds the
indices of elements of A greater than 1.

Kamaraj College of Engineering and


Technology 4/2/2019
 MATLAB supports 8 formats for outputting numerical
results.
format long 16 digits
format short e 5 digits plus exponent
format long e 16 digits plus exponent
format hex hexadecimal
format bank two decimal digits
format + positive, negative or zero
format rat rational number (215/6)
format short default display

Kamaraj College of Engineering and


Technology 4/2/2019
 MATLAB supports six relational operators.

Less Than <


Less Than or Equal <=
Greater Than >
Greater Than or Equal >=
Equal To ==
Not Equal To ~=

Kamaraj College of Engineering and


Technology 4/2/2019
 MATLAB supports three logical operators.

not ~ % highest precedence


and & % equal precedence with or
or | % equal precedence with and

Kamaraj College of Engineering and


Technology 4/2/2019
Power ^ or .^ a^b or a.^b
Multiplication * or .* a*b or a.*b
Division / or ./ a/b or a./b
or \ or .\ b\a or b.\a
NOTE: 56/8 = 8\56

Addition + a+b
Subtraction - a-b
Assignment = a=b (assign b to a)

Kamaraj College of Engineering and


Technology 4/2/2019
PRECEDENC MATHEMATICAL OPERATIONS
E
First The contents of all parentheses are evaluated first,
starting
from the innermost parentheses and working
outward.
Second All exponentials are evaluated, working from left to
right
Third All multiplications and divisions are evaluated,
working from left to right
Fourth All additions and subtractions are evaluated, starting
from left to right

Kamaraj College of Engineering and


Technology 4/2/2019
sqrt(x) – square root
sin(x) – sine function. See also cos(x), tan(x), etc.
exp(x) – exponential
log(x) – natural log
log10(x) – common log
abs(x) – absolute value
mod(x) – modulus
factorial(x) – factorial function
floor(x) – round down. See also ceil(x), round(x).
min(x) – minimum elements of an array.
max(x) – maximum elements of an array

Kamaraj College of Engineering and


Technology 4/2/2019
>> prompt
... continue statement on next line
, separate statements and data
% start comment which ends at end of line
; (1) suppress output
(2) used as a row separator in a matrix
: specify range

Kamaraj College of Engineering and


Technology 4/2/2019
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

Kamaraj College of Engineering and


Technology 4/2/2019
 Special matrix in which most of the elements are zero.
 Matlab has powerful techniques for handling sparse matrices.
These are generally large matrices (to make the extra work
involved worthwhile) that have only a very small proportion
of non zero entries.

Kamaraj College of Engineering and


Technology 4/2/2019
Create a sparse 5 4 matrix S having only 3 non{zero values: S1;2 =
10, S3;3 = 11 and S5;4 = 12.We rst create 3 vectors containing the
i{index, the j{index and the corresponding values ofeach term and
we then use the sparse command.
OUTPUT
S=
(1,2) 10
>> i = [1, 3, 5]; j = [2,3,4]; (3,3) 11
(5,4) 12
>> v = [10 11 12]; T=
>> S = sparse (i,j,v) 0 10 0 0
0000
>> T = full(S) 0 0 11 0
0000
0 0 0 12

Kamaraj College of Engineering and


Technology 4/2/2019
fopen – open a file for reading or writing
fread – read a binary file
fscanf – read an ASCII file
fwrite – write a binary file
fprintf – write an ASCII file
fclose – close a file (when you are done with it)

Kamaraj College of Engineering and


Technology 4/2/2019
>> fid = fopen(‘file1.dat’, ‘r’);
>> A = fread(fid);
>> fclose(fid);
The ‘r’ specifies that the file is to be opened for reading (‘w’ for writing, ‘r+’
for reading
and writing, ‘a’ for appending). In this example, the contents of file1.dat were
read into a
single-column matrix A. If you wanted to read in A as a 3x3 matrix you
would type:
>> fid = fopen(‘file1.dat’, ‘r’);
>> A = fread(fid, [3 3]);
>> fclose(fid);

Kamaraj College of Engineering and


Technology 4/2/2019
 fgetl – capture one line at a time from the input file
 feof – check whether the end-of-file has been reached
 fseek/ftell – get and set file position
 frewind – go back to the beginning of the file

Kamaraj College of Engineering and


Technology 4/2/2019
 MATLAB supports reading an entire file and creating a matrix of
the data with one statement.
>> load mydata.dat; % loads file into matrix.
% The matrix may be a scalar, a vector, or a
% matrix with multiple rows and columns. The
% matrix will be named mydata.
>> size (mydata) % size will return the number
% of rows and number of
% columns in the matrix
>> length (myvector) % length will return the total
% no. of elements in myvector

Kamaraj College of Engineering and


Technology 4/2/2019
 Use the “set”
 command to change the limits on the y-axis:
 >> set(gca, y)
 The “gca” means “get handle to current axis”. The
“set” command can be used to set any
 properties of your figure.lim’, [0 50])

Kamaraj College of Engineering and


Technology 4/2/2019
 MATLAB 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. The vectors have to be the same length.
 MATLAB will also plot a vector vs. its own index. The index will
be treated as the abscissa vector. Given a vector “time” and a vector
“dist” we could say:
>> plot (time, dist) % plotting versus time
>> plot (dist) % plotting versus index

Kamaraj College of Engineering and


Technology 4/2/2019
 There are commands in MATLAB to "annotate" a plot to put on axis
labels, titles, and legends. For example:
>> % To put a label on the axes we would use:
>> xlabel ('X-axis label')
>> ylabel ('Y-axis label')

>> % To put a title on the plot, we would use:


>> title ('Title of my plot')

Kamaraj College of Engineering and


Technology 4/2/2019
 Vectors may be extracted from matrices. Normally, we wish to plot
one column vs. another. If we have a matrix “mydata” with two
columns, we can obtain the columns as a vectors with the
assignments as follows:

>> first_vector = mydata ( : , 1) ; % First column


>> second_vector = mydata ( : , 2) ; % Second one
>> % and we can plot the data
>> plot ( first_vector , second_vector )

Kamaraj College of Engineering and


Technology 4/2/2019
 >> colormap(gray)
 If you want to see the color scale on the figure, type
“colorbar

Kamaraj College of Engineering and


Technology 4/2/2019
function f = incrementor(x,c)
% Incrementor adds c to each element in the matrix x.
f = x + c;
>> incrementor(A,1)
ans =
222
333
444

Kamaraj College of Engineering and


Technology 4/2/2019
 function [v] = MySort(u)
 %|This function sorts vector u in %|increasing order, returning the sorted vector as v.
%Determine length of vector
 n = length(u);
 %Copy vector u to v
 v = u;
 %Start sorting process
 for i = 1:n-1
 for j = i+1:n
 if v(i)>v(j)
 temp = v(i);
 v(i) = v(j);
 v(j) = temp;
 end
 end
 end

Kamaraj College of Engineering and


Technology 4/2/2019
 An if - elseif - else structure in MATLAB.
Note that elseif is one word.

if expression1 % is true
% execute these commands
elseif expression2 % is true
% execute these commands
else % the default
% execute these commands
end

Kamaraj College of Engineering and


Technology 4/2/2019
 A for loop in MATLAB for x = array
for x = 1: 0.5 : 10
% execute these commands
end

 A while loop in MATLAB while expression


while x <= 10
% execute these commands
end

Kamaraj College of Engineering and


Technology 4/2/2019
 MATLAB provides several flow control statements that you can use in scripts. These
 include:
 FOR loops:
 for i = 1:10
 a(i) = 2;
 end
 WHILE loops:
 while a(i) ~= 0
 b(i) = 1/a(i);
 end
 IF/ELSE statements:
 if i > 0
 a(i) = 1;
 else
 a(i) = 0;
 end
 The “break” statement can be used to exit from the current FOR or WHILE loop.
Kamaraj College of Engineering and
Technology 4/2/2019
THANK YOU

Kamaraj College of Engineering and


Technology 4/2/2019

Das könnte Ihnen auch gefallen