Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Introduction To Matlab

Download as pdf or txt
Download as pdf or txt
You are on page 1of 10

Introduction to Matlab

The name “Matlab” stands for matrix laboratory. Matlab is a high performance
computing language. Matlab has many advantages compared to conventional
computer language for solving technical problems.

1. Starting Matlab: -
When you start Matlab a special window called the Matlab desktop appears. The
Desktop is a window that contains other windows, the major tools within or
accessible from the desktop are:
1. The Command window (>> prompt)
2. The Command History
3. The Workspace
4. The Current Directory
For example you want to calculate 1+2 x 3
>> 1+2*3
Ans.
=7
You will notice that if you don’t specify an output variable, Matlab uses a default
variable ans.
To avoid this, you may assign a value to a variable or output argument name e.g.
>> X = 1+2*3
X
=7

2. Creating Matlab Variables:-


Matlab variables are created with an assignment statement. The syntax of variable
assignment is
Variable name = a value (or an expression)
e.g.
X = expression
Expression can involve
 Manual entry
 Built in function
 User defined function
3. Over writing variable: -
Once a variable has been created it can be reassigned
t = 5;
t = t+1
t=6

4. Error messages:-
If you enter an expression incorrectly, Matlab will return an error messages.
>> X = 10;
>> 5X (incorrect)
>> 5*X (correct)
To make corrections, we can retype the expressions. But if the expressions is
lengthy, you can recalled the command with the up – arrow key ↑. When command
is prompt, it can be modified if needed and executed.
Controlling the hierarchy (order) of operation:-
Ex: 1+2x3
>> (1+2)*3 Ans = 9
>> 1+2*3
>> Ans = 7.
The order in which Matlab performs arithmetic operations is exactly that taught in
high school algebra courses.

5. Controlling the appearance of the floating point number:-


Matlab by default displays only 4 decimals in the result of calculations.
If we want to see 15 digits, we use the command format long.
To return to the standard format enter format short or simply shorts.
There are several other formats, type help format.
Note: - We have let Matlab to repeat everything that we enter at the prompt.
To prevent Matlab from doing we simply enter a semi colon (;) at the end of
command
>> x = 163.667;

6. Managing the workspace:-


The contents of the workspace persist between the executions of separate
commands. Therefore it is possible for the result of one problem to have an effect
on the next one. To avoid two possibility it is a good idea to issue a clear command
at the start of each new independent calculations.
>> Clear
Or >> Clear all
This command clear or clear all removes all variables from the workspace. This
frees up system memory. In order to display a list of the variable currently in the
memory type
>> Who

7. Entering multiple statements per line:-


Use commas (,) or semicolons (;) to enter more than one statement at once commas
(,) allow multiple statements per line without suppressing output.
>> a = 7 ; b = cos(a) , c = cosh(a)
B=
0.6570
C=
548.3170

8. Getting help:-
Information about any command is available by typing
>> help command
The help command searches for an exact function name match
>> help inv
The lookfor command differs from the help command. The help command
searches for an exact function name match while the lookfor command searches
the quick summary information in each function for match.
>> help inverse (No result)
On the other hand the command lookfor inverse will produce detailed information
which includes the function of interest.
>> Lookfor inverse
The doc function opens the on – line version of the help manual.
>> Doc plot

9. Mathematical function:-
There is a long lost of mathematical function that are built into Matlab. These
functions are called built – ins. Many standard mathematical function such as
sin(x), cos(x), tan(x), 𝑒 𝑥 , ln(x) are evaluated by the functions sin, cos, tan, exp, log
respectively
Cos(x) cosine
Sin(x) sine
Tan(x) tangent
Acos(x) Arc cosine
Asin(x) Arc Sine
Exp(x) exponential
Sqrt(x) square Root
Log(x) Natural log
Log10(x) common logarithm
In addition to elementary function Matlab includes a No. of predefined constant
values e.g. pi, inf, Nan
Typing help elfun and help specfun calls up the lists of elementary and special
functions respectively.
e.g.
𝑦 = 𝑒 −𝑎 sin 𝑥 + 10√𝑦 for a = 5, x = 2, y = 8
>> a = 5 ; x = 2; y = 8;
Y = exp(-a)* sin(x)+10*sqrt(y)
Y = 28.2904

10. Ploting:-
In 2D, Matlab graph we have to take a vector of x coordinates x = (x1, ---------- xN)
and a vector of y – coordinates y = (y1 ---------- yN) you need to prepare x and y in
an identical array form, namely x f y are both row arrays and column arrays of
same length.
The Matlab command to plot a graph is
Plot (x , y)
Ex.
X = (1,2,3,4,5,6)
Y = (3,-1,2,4,5) To proceed
>> x = [1 2 3 4 5 6];
>> y = [3 -1 2 4 5 1];
>> plot (x , y)
Plot (x , y) produces graph of y versus x.
Ex 2.
To plot the function sin(x) on the interval [0, 2π]. Use first create a vector of x
values ranging from o to 2π, the complete the sine of these values and finally plot
the result.
>> x = 0 : pi/2 : 2*pi;
>> y = sin(x);
>> plot (x,y)
0 : pi/100 : 2*pi yields a vector that
 Starts at 0
 Takes increment of π/100
 Stops when 2π is reached
If you omit the increment, Matlab automatically increments by 1.
Adding titles, axis labels
MATLAB enables you to add axis labels and titles.
Note the character |pi creates the symbol π
>> xlabel (‘x = 0:2/pi’)
>> ylabel(‘sin of x’)
>> title (‘plot of the sine function’)

11. Matrix Generation:-


Matrices are basic elements of the Matlab environment. A matrix is a two
dimensional (m x n) array consisting of m rows and n columns.
A vector is a special case of a matrix. An array of dimension 1 x n is called a row
vector whereas an array of dimensions m x 1 is called a column vector.
The elements of vectors is Matlab are enclosed by square brackets and are
separated by spaces or by commas.
Example.
To enter a row vector, v, type
>> v = [1 4 7 10 13]
V=
1 4 7 10 13
Column vector are created in a similar way however, semicolon (;) must separate
the components of a column vector.
>> W = [1; 4; 7]
W=
1
4
7
A row vector is converted to a column vector using the transpose operator. The
transpose operation is devoted by an apostrophe or a single quote (‘).
>> W = V’
W=
1
4
7
10
13
To access blocks of elements, we use colon notation (:)
Example:
To access the first three elements of V
We write
>> V (1:3)
Ans =
1 4 7
Or all elements from the third through the last elements
>> V (3, end)
Ans =
7 10 13
Where end signigies the last element in the vector. If V is a vector, writing >> V (:)
produces a column vector, whereas writing >> V (1: end) produces a row vector.

12. Entering a matrix:-


A matrix is an array of numbers. To type a matrix into Matlab you must
 Begin with a square bracket, [
 Separate elements in a row with spaces or commas (,)
 Use a semicolon (;) to separate rows
 End the matrix with another square bracket,]
To end a matrix A, type
>> A = [1 2 3 ; 4 5 6 ; 7 8 9]
A=
1 2 3
4 5 6
7 8 9
We can view a particular element in matrix in specifying its location. We wrote
>> A (2 , 1)
Ans =
4
13. Matrix Indexing:-
The elements of row i and column j of the matrix A is denoted by A (I , j). The first
index is the row number and second index is the column number.
Correcting any entry is easy through indexing. Here we substitute A (3 , 3) = 9 by
A (3 , 3) = 0. The result is
>> A (3 , 3) = 0
A=
1 2 3
4 5 6
7 8 0

14. Colon operator:-


Often we must deal with matrices or vectors that are too long to enter one elements
at a time.
Example:-
We want to enter a vector x consisting of points (0, 0.1, 0.2, --------, 5). We type
>> x = 0 : 0.1 : 5;

15. Linear spacing:-


To get direct control over the number of points we use linespace y = (a ,b, n)
generates a row vector y of n points linearly spaced between and including a and b.
Example:-
Theta = linespace (0, 2*pi, 101)
Divides the interval [0,2π] into 100 equal subintervals, then creating a vector of
101 elements.

16. Colon operator in a matix:-


Colon operator can also be used to pick out a certain row or column. For example,
the statements A (m:n , k:l) specifies rows m to n and column k tol.
Example:-
>> A (2, :)
Ans =
4 5 6
If the second row elements of A. It can also be used to extract a sub matrix from a
matrix A.
>> A(:,2:3)
Ans
=
2 3
5 6
8 0
A row or a column of a matric can be detected by setting it to a null vector, [].
>> A (: , 2) = [ ]
Ans =
1 3
4 6
7 0
>> A (end , :)
Picks out the last row of A

17. Dimensions:-
To determine the dimensions of a matrix or vector use the command size.
Example:-
>> Size (A)
Ans =
3 3
Means 3 rows and 3 columns

18. Matrix generators:-


Matlab provides functions that generates elementary matrices.

19. Elementary Matrices:-


Eye (m , n) Returns m x n matrix with 1 on the main diagonal
Eye (n) Returns n x n square identity matrix
Zeros (m , n) Returns m x n matrix of zeros
Ones (m , n) Returns m x n matrix of ones
Diagonal (A) Extract the diagonal of matrix A
Rand (m , n) Returns a m x n matrix of random numbers
For complete list of elementary matrices type helpelmat or doc elmat.

20. Matric arithmetic operations:-


Matlab allows arithmetic operations to be carried out on matrices.
A + B or B + A is valid if A & B are of the same size
A*B is valid if A’s number of columns equals to B’s number
of rows.
A^2 is valid if A is square and equals A*A
α*A or A*α multiplies each element of A by α

21. Matrix Inverse:-


In Matlab, the following command is used to find the inverse of matrix.
>> A = [1 2 3 ; 4 5 6 ; 7 8 0];
>> inv(A)
Ans =
-1.7778 0.8889 -0.1111
1.5556 -0.7778 0.22222
-0.1111 0.2222 -0.1111

22. Determinant:-
The determinant of A is
>> det (A)
Ans =
27

23. Control flow:-


Matlab has four control flow structures. The control if statement, the for loop, the
while loop and the switch statement
The “if ------ end” structure:-
If Expression
Statements
End
Example:
1. discr = b*b – 4*a*c;
If discr < 0
Disp (‘discriminant is negative’);
End
The “for -------- end” loop:-
For variable = expression
Statements
End
Example:-
For a = 1.0 ; -0.1 : 0.0
Disp (a)
end

You might also like