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

Fem - Matlab Basics

Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Fem - Matlab Basics

Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 49

MATLAB

MATLAB Basics SCEGE


BASICS

MATLAB Basics

Lecturer: Dr. Gilford B. Estores


MATLAB
INTRODUCTION TO MATLAB SCEGE
BASICS

What is MATLAB?

- The name stands for MATrix LABoratory


- MATLAB is a high-performance language for technical
computing. It integrates computation, visualization, and
programming environment.
- MATLAB is a modern programming language
environment: it has sophisticated data structures,
contains built-in editing and debugging tools, and
supports object-oriented programming.

1
MATLAB
INTRODUCTION TO MATLAB SCEGE
BASICS

THE MATLAB SYSTEM

- Development Environment
- The MATLAB Mathematical Function Library
- The MATLAB Language
- The MATLAB Application Program Interface (API)

2
MATLAB
INTRODUCTION TO MATLAB SCEGE
BASICS

Development Environment

- Set of tools and facilities that help use MATLAB


functions and files.
- Includes:
- MATLAB Desktop
- Command Window
- Command History
- Editor and Debugger and browsers for viewing help
- Workspace

3
MATLAB
INTRODUCTION TO MATLAB SCEGE
BASICS

MATLAB MATHEMATICAL FUNCTION LIBRARY


- This is a vast collection of computational algorithms
ranging from elementary functions
Examples:
> sum, sine, cosine, and complex arithmetic
> sophisticated functions like matrix inverse, matrix
eigenvalues, Bessel functions, and fast Fourier
transforms.

4
MATLAB
INTRODUCTION TO MATLAB SCEGE
BASICS

MATLAB LANGUAGE

- This is a high-level matrix/array language with control


flow statements, functions, data structures,
input/output, and object-oriented programming
features.
- It allows both "programming in the small" to rapidly
create quick and dirty throw-away programs, and
"programming in the large" to create complete large
and complex application programs.

5
MATLAB
INTRODUCTION TO MATLAB SCEGE
BASICS

GRAPHICS
- MATLAB has extensive facilities for displaying vectors
and matrices as graphs, as well as annotating and
printing these graphs.
- It includes high-level functions for two-dimensional and
three-dimensional data visualization, image processing,
animation, and presentation graphics.
- It also includes low-level functions.

6
MATLAB
INTRODUCTION TO MATLAB SCEGE
BASICS

MATLAB APPLICATION PROGRAM INTERFACE

- This is a library that allows you to write C and Fortran


programs that interact with MATLAB.
- It includes facilities for calling routines from MATLAB
(dynamic linking), calling MATLAB as a computational
engine, and for reading and writing MAT-files.

7
MATLAB
INTRODUCTION TO MATLAB SCEGE
BASICS

Entering Commands and Expressions

The prompt >> is displayed in the Command


Window and when the Command Window is
active, a blinking cursor should appear to the right
of the prompt.
This cursor and the MATLAB prompt signify that
MATLAB is waiting to perform a mathematical
operation.

8
MATLAB
FUNDAMENTAL CONCEPTS SCEGE
BASICS
Commands for Managing a Session
- Removes all the variables from the
clear workspace.
- Frees up system memory
- Displays the list of variables currently in
who
the memory.
- Will display more details which include
whos size, space, allocation and class of
variables
exist - Checks for existence of the variable.
global - Declares variable to be global.
help - Searches for help topic
lookfor - Searches help entries for keyword
quit - Stops the MATLAB
9
MATLAB
FUNDAMENTAL CONCEPTS SCEGE
BASICS

Help Features in MATLAB

helpbrowser Opens the help window


Displays the help document in the
help function_name
command window
Displays the help document in
helpwin function_name
separate window
doc function_name Displays detailed help document in
separate window

10
MATLAB
FUNDAMENTAL CONCEPTS SCEGE
BASICS

Numeric Display Formats


- Controls the display output of the command
format
window
Common Format Functions
short - Four decimal digits
long - Sixteen decimal digits
short e - Five decimal digits plus exponent
long e - Sixteen digits plus exponent
bank - Two decimal digits

11
MATLAB
FUNDAMENTAL CONCEPTS SCEGE
BASICS

Mathematical Functions

Special Variables and Constants

ans - Most recent answer


i, j - The imaginary unit
Inf - Infinity
NaN - Undefined numerical result (not a number)
pi - The number

12
MATLAB
FUNDAMENTAL CONCEPTS SCEGE
BASICS

Mathematical Functions
Elementary Functions
cos(x) Cosine abs(x) Absolute value
sin(x) Sine ceil(x) Round towards + Inf
tan(x) Tangent floor(x) Round towards - Inf
acos(x) Arc cosine round(x) Round
asin(x) Arc sine rem(x) Remainder after division
atan(x) Arc tangent angle(x) Phase
exp(x) Exponential conj(x) Complex Conjugate
sqrt(x) Square root imag (x) imaginary
Natural
log(x) real (x) Real number
Logarithm
Common
log10(x) primes (x) Prime Number
Logarithm 13
MATLAB
FUNDAMENTAL CONCEPTS SCEGE
BASICS

Mathematical Functions
Scalar Arithmetic

Symbol Operation

+ Addition

- Subtraction

* Multiplication

/ Right Division

\ Left Division

^ Exponentiation

14
MATLAB
FUNDAMENTAL CONCEPTS SCEGE
BASICS

Mathematical Functions

Exponential and Logarithmic Functions

exponential exp (x)


Natural Logarithm log (x)
Common Logarithm log10 (x) = [ log10 (x) ]
Square root sqrt (x)

15
MATLAB
ARRAYS AND MATRICES SCEGE
BASICS

One of the strengths of MATLAB is the


capability to handle collections of numbers, called
arrays, as if they were a single variable. Single
numbers are called scalars, whereas, arrays are
collections of scalars arranged in a specific order.

An example of an array variable is one that


contains the numbers 0, 1, 3, and 6, in the order.
We can use square brackets to define the variable
x to contain this collection by typing
>>x = [ 0, 1, 3, 6].

16
MATLAB
ARRAYS AND MATRICES SCEGE
BASICS

17
MATLAB
ARRAYS AND MATRICES SCEGE
BASICS

18
MATLAB
ARRAYS AND MATRICES SCEGE
BASICS

CREATING ARRAYS
A. ROW VECTOR
Type the elements inside a pair of square
brackets, separating the elements inside with a
space or a comma.
Example:
>>A = [10 –3 4 6] or
>>A = [10, –3, 4, 6]

19
MATLAB
ARRAYS AND MATRICES SCEGE
BASICS

B. COLUMN VECTOR

Separate the elements by semicolons or


create a row vector first and then use the
transpose notation ( ‘ ) which converts a row
vector into a column vector, or vice versa.
Example:
>>B=[–5; 3; 6; 0; 2] or
>>B=[–5, 3, 6, 0, 2]’

20
MATLAB
ARRAYS AND MATRICES SCEGE
BASICS

Another way is to type a left bracket and


the first element, press ENTER, type the
second element, press ENTER, and so on until
you type the last element followed by the right
bracket.
Example:
>>B=[–5
3
6
0
2]
21
MATLAB
ARRAYS AND MATRICES SCEGE
BASICS

C. MATRICES

22
MATLAB
ARRAYS AND MATRICES SCEGE
BASICS

APPENDING ARRAYS

23
MATLAB
ARRAYS AND MATRICES SCEGE
BASICS

SPECIAL WAY OF CREATING


MATRICES
1. Using :
The colon ( : ) generates a vector of
regularly spaced elements. Typing
>>x = [m: q: n]
creates a vector x with first value m and last
value n with a spacing q. The last value is
less than n if m – n is an integer not multiple
of q.

24
MATLAB
ARRAYS AND MATRICES SCEGE
BASICS

Example:
>>x = [2: 2: 8]
>>y = [1: 3: 11]
>>z = [20: –2: 10]
If q is omitted, it is presumed to be 1.
Example:
>>w = [–3: 2]

25
MATLAB
ARRAYS AND MATRICES SCEGE
BASICS

2. Using linspace
Linspace command creates a linearly spaced
row vector by specifying the number of
elements rather than the increment. The syntax
>>x = [a, b, n] means creating a vector x
where a and b are the lower and upper limits,
respectively and n is the number of elements.
Example:
>>linspace (5, 8, 31).
It contain 31 elements. If n is omitted, the
default value is 100.
26
MATLAB
ARRAYS AND MATRICES SCEGE
BASICS

3. Using logspace
It creates an array of logarithmically spaced
elements. The syntax is
>>logspace (a, b, n)
where n is the number of elements between
10a and 10b.
Example:
>>x = logspace (–1, 1, 6)
If n is omitted, the number of elements defaults
to 50.

27
MATLAB
ARRAYS AND MATRICES SCEGE
BASICS

SOME USEFUL ARRAY FUNCTIONS


Functions Descriptions
magic(n) creates an n x n matrix where the
sum of its diagonal, rows and
columns are equal
eye(n) creates an n x n identity matrix
ones(n) creates an n x n matrix of ones
ones(m,n) creates an m x n matrix of ones
zeros(n) creates an n x n matrix of zeros
zeros(m,n) creates an m x n matrix of zeros
28
MATLAB
ARRAYS AND MATRICES SCEGE
BASICS

SOME USEFUL ARRAY FUNCTIONS


size(A) returns a row vector [m, n] containing the
sizes of the m x n array A

length(A) computes either the number of elements


of A if A is a vector or the largest value of
m or n if A is an m x n matrix

sum(A) sums the elements in each column of the


array A and returns a row vector
containing the sums
sort(A) sorts each column of the array A in
ascending order and returns an array the
same size as A 29
MATLAB
ARRAYS AND MATRICES SCEGE
BASICS

SOME USEFUL ARRAY FUNCTIONS

max(A) returns the algebraically largest


element in A if A is a vector. Returns
a row vector containing the largest
elements in each column if A is a
matrix
min(A) same as max(A) but returns
minimum values
diag(A) returns the main diagonal of A

30
MATLAB
ARRAYS AND MATRICES SCEGE
BASICS

ARRAY OPERATIONS
(Element-by-element operations)
Symbols Operations
+ Scalar-array addition
– Scalar-array subtraction
+ Array addition
– Array subtraction
.* Array multiplication
./ Array right division
.\ Array left division
.^ Array exponentiation 31
MATLAB
ARRAYS AND MATRICES SCEGE
BASICS

MATRIX OPERATIONS
Applies the same rule in ordinary matrices
operations in Mathematics.
Note:
1. + and – apply the same rule as in element-
by-element operations.
2. A/B = A*B-1 , where B-1 is the inverse of B.
3. A^2 = A*A
4. AB is not defined .

32
MATLAB
ARRAYS AND MATRICES SCEGE
BASICS

Determinants

33
MATLAB
GRAPHICS-2D SCEGE
BASICS

FIGURE WINDOWS
MATLAB directs graphics output to a
window called figure that is separate
from the command window. The figure
function creates figure windows.

Example: >>figure

34
MATLAB
GRAPHICS-2D SCEGE
BASICS

2-D Plotting
The plot function is used to produce two-
dimensional curves, using x- and y-data
matricesspecified by the user.
plot(xdata,ydata,’cml’)

You can plot multiple lines at once, using pairs


of x- and y-data, or triples of x, y.
plot(x1,y1,’clm1’,x2,y2,’cml2’)

35
MATLAB
GRAPHICS-2D SCEGE
BASICS

Examples:
>> x = 0:10 ;
>> y = 2*x + 3;
>> plot(x,y)

>> y1 = 4*x – 2;
>> y2 = x + 2;
>> plot(x,y1,x,y2)

36
MATLAB
GRAPHICS-2D SCEGE
BASICS

Adding a Grid
grid on creates a
grid on the current
figure

grid off turns off the


grid from the current
figure

grid toggles the grid


state

37
MATLAB
GRAPHICS-2D SCEGE
BASICS

Color, Line Style and Marker


The user can specify the color, line style and marker
of a graph. If not, a blue solid line without marker
symbols, is produced. Some of them are:

38
MATLAB
GRAPHICS-2D SCEGE
BASICS

Graph a red sine


wave
>> x = 0:0.1:2*pi;
>> y = sin(x);
>> plot(x,y,’ro’)
>> grid on
>> axis equal

39
MATLAB
GRAPHICS-2D SCEGE
BASICS

Adding Additional Plots to a Figure


By default, plot deletes existing lines and resets all axis
properties when a new line is drawn.

hold on holds the current plot

hold off releases hold on the current plot

hold toggles the hold state

40
MATLAB
GRAPHICS-2D SCEGE
BASICS

Add graph of magenta


cosine wave
>> x = 0:0.1:2*pi;
>> y = sin(x);
>> plot(x,y,’ro’)
>> grid on
>> axis equal
>> y1=cos(3*x);
>> hold on
>> plot(x,y1,’m*-’)
41
MATLAB
GRAPHICS-2D SCEGE
BASICS

Displaying Multiple Plots per Figure


Format: subplot(m,n,i)
This function breaks the figure window into m-by-n matrix of
small subplots and selects the ith subplot for the current plot.

Example:

subplot(2,2,i)
1 2
where i = 1 to 4

>> subplot(2,2,1)
>> subplot(2,2,2)
>> subplot(2,2,3) 3 4
>> subplot(2,2,4)
42
MATLAB
GRAPHICS-2D SCEGE
BASICS

ezplot
ezplot is an easy to use function plotter for algebraic and
transcendental functions, parametric equations, implicit and
explicit functions.
ezplot(f)
plots the expression f = f(x) over the default
domain -2 < x < 
ezplot(f,[a,b])
plots f = f(x) over a < x < b
Examples:
>> ezplot(‘cos(x)’)
>> ezplot(‘1/y-log(y)+log(-1+y)+x-1’)
>> ezplot(‘x^2+y^2-4’,[-3,3])
43
MATLAB
LIVE SCRIPT SCEGE
BASICS

What is a Live Script?

A MATLAB live script is an interactive document


that combines MATLAB code with embedded
output, formatted text, equations, and images in a
single environment called
the Live Editor. Live scripts are stored using
the Live Script file format in a file with
a .mlx extension.

44
MATLAB
LIVE SCRIPT SCEGE
BASICS

Use live scripts to:


1. Visually explore and analyze problems
Write, execute, and test code in a single interactive environment.
Run blocks of code individually or as a whole file, and view the results and
graphics with the code that produced them.

2. Share richly formatted, executable narratives


Add titles, headings, and formatted text to describe a process and
include LaTeX equations, images, and hyperlinks as supporting material.
Save your narratives as richly formatted, executable documents and share them
with colleagues or the MATLAB community, or convert them to HTML or PDF files
for publication.

3. Create interactive lectures for teaching


Combine code and results with formatted text and mathematical equations.
Create step-by-step lectures and evaluate them incrementally to illustrate a topic.
Modify code on the fly to answer questions or explore related topics.
Share lectures with students as interactive documents or in hardcopy format, and
distribute partially completed files as assignments.
44
MATLAB
LIVE SCRIPT SCEGE
BASICS

Format Live Scripts


You can add formatted text, hyperlinks, images, and equations to your
live scripts to create a presentable document to share with others.
To insert an item, go to the Live Editor tab and in the Insert section,
select one of these options:

• Code — This inserts a blank line of code into your live script. You can
insert a code line before, after, or between text lines.

• Text — This inserts a blank line of text into your live script. A text line
can contain formatted text, hyperlinks, images, or equations. You can
insert a text line before, after, or between code lines.

•Section Break — This inserts a section break into your live script. Insert
a section break to divide your live script into manageable sections that
you can evaluate individually. In live scripts, a section can consist of
code, text, and output. For more information, see
Run Sections in Live Scripts.
44
MATLAB
LIVE SCRIPT SCEGE
BASICS

• Equation — This inserts an equation into your live script. Equations can only be
added in text lines. If you insert an equation into a code line, MATLAB places the
equation in a new text line directly under the selected code line. For more
information, see Insert Equations into Live Scripts

• Hyperlink — This inserts a hyperlink into your live script. Hyperlinks can only be
added in text lines. If you insert a hyperlink into a code line, MATLAB places the
hyperlink in a new text line directly under the selected code line.

• Image — This inserts an image into your live script. Images can only be added in
text lines. If you insert an image into a code line, MATLAB places the image in a
new text line directly under the selected code line.

Format Text
You can further format text using any of the styles included in the Text
Style section. Use the down arrow to the right of the section to display all the
available text style options. Styles include Normal, Heading, Title, Bulleted List,
and Numbered List.

44
MATLAB
LIVE SCRIPT SCEGE
BASICS

Save Live Script as Script

To save a live script as a plain code file (.m).


1.On the Live Editor tab, in the File section,
select Save > Save As....
2.In the dialog box that appears, select MATLAB
Code files (*.m) as the Save as type.
3.Click Save.
When saving, MATLAB converts all formatted
content to publish markup.

44

You might also like