MATLAB basics - PowerPoint PPT Presentation

1 / 29
About This Presentation
Title:

MATLAB basics

Description:

MATLAB basics Get to know Matlab Interact with Matlab Write and save a program Run and debug a program Loop and for loop structure Simple 2D plotting – PowerPoint PPT presentation

Number of Views:230
Avg rating:3.0/5.0
Slides: 30
Provided by: clark250
Category:

less

Transcript and Presenter's Notes

Title: MATLAB basics


1
MATLAB basics
  • Get to know Matlab
  • Interact with Matlab
  • Write and save a program
  • Run and debug a program
  • Loop and for loop structure
  • Simple 2D plotting
  • Get help in Matlab

2
Uses of MATLAB
  • MATLAB is a sophisticated mathematical
    computation tool. It has many capabilities,
    including
  • Mathematical operations
  • Computations with matrices
  • Symbolic calculations
  • Graphical capabilities, including many plotting
    features
  • MATLAB can be used in many engineering
    applications.

3
MATLAB Desktop
Command Window Workspace Window Current
Directory Window Command History Window Start
Button
clc clears the command window clear clears
the workspace
4
Interacting with MATLAB
Scalar variables
matrices
  • Type in the Command Window
  • 22
  • The solution was stored in the default variable
    ans.
  • Then type
  • clear
  • Now define C_as
  • C_as0.6
  • The semi-colon () prevents the result from being
    printed to the screen
  • Only letters, numbers and _ can be used.
  • Case sensitive.
  • Define 1D matrix (vector) x
  • x10.24 or
  • xones(4,1)
  • The first index is the number of rows and the
    second index is the number of columns.
  • The solution can also be viewed in workspace.
  • Then define a 2D matrix
  • y1,2,34,5,6
  • We can change the value of any elements
  • y(2,3)5
  • The matrix dimension can also be changed
  • y(4,4)7

5
Writing a Program
  • A MATLAB program can be a collection of command
    lines and is in the form of an M-file
  • An M-file is to MATLAB what a doc-file is to
    Microsoft Word.
  • An M-file is written in text Editor.
  • M-files can be used to
  • write programs
  • save and reopen a program
  • Fix errors in a program

6
Writing an M-File
  • Create a new M-file
  • Type edit into the Command Window
  • or use the menu File
  • Type the following code in the Editor
  • epsilon10
  • C_as0.5
  • r0R/20R
  • R5
  • rhor/R
  • To insert a comment line in an M-file, use the
    comment operator , then type in your comment.
  • After you have typed the code, save it as
    concentration.m

7
Commenting
  • Every time you write a program, it should be
    well-commented.
  • MATLAB
  • will not run lines that begin with the comment
    operator
  • shades comments in green
  • Commenting can explain
  • what the program does
  • what the variables in the program represent
  • any calculations in the program
  • allow programmers to more easily understand your
    program
  • make difficult operations easier to understand
  • document when code was written and by whom
  • define variables used
  • help clarify your own thinking

8
Changing the Directory
  • To change your directory, click the Browse for
    Folder button next to where the Current
    Directory is shown.
  • Navigate through this window to My Computer and
    then to where you want to save your M file and
    click OK.
  • You should make sure that your Current Directory
    is where your file is, otherwise Matlab will not
    run it.

9
Running an M-file
  • Make sure that your Current Directory is where
    your file is. Type concentration into the Command
    Window and press enter, or use the Debug menu.
  • If you typed the code as written on the previous
    slide you will get an error. What went wrong?
  • Error checking, also called debugging, helps to
    verify a program works properly.
  • The advantage of an M-file is that we can go make
    the change and run it again without having to
    type all the code again.

10
Syntax Errors
  • Syntax errors are errors in a MATLAB statement
    itself, such as spelling or punctuation errors.

sni(pi) ln(x) z 1,2,3,4,5
sin(pi) log(x) z 1,2,3,4,5
Built-in functions sin, cos, log are built-in
functions in MATLAB. There are more built-in
functions we will be using in this class, they
are besseli, besselj, besselk, bessely,
gamma For more information on these functions,
please use help.
11
Run-Time Errors
  • Run-time errors occur when illegal operations are
    attempted during program execution.
  • One run-time error occurs when attempting to
    access an element in a matrix that exceeds the
    dimensions of that matrix.
  • Type the following into the Command Window
  • a rand(3,4)
  • b a(7,1)
  • There are not 7 rows in the matrix A, so an error
    message is generated.

12
Logical Errors
  • Logical errors occur when the program runs
    without displaying an error, but produces an
    unexpected result.
  • Such errors can be very difficult to find. We can
    compare simple test cases with known correct
    results in an attempt to find where these errors
    occur.
  • For example, the following code is meant to
    determine the volume of a sphere
  • V(4/3)pir2
  • Where is the error?

13
The Concept of For Loops
  • Loops are MATLAB constructs that allow a sequence
    of MATLAB statements to be executed more than
    once.
  • For loops repeat a block of commands for known
    number of times before the loop is executed.
  • For loop syntax
  • for index index matrix
  • command 1
  • command 2
  • .
  • .
  • end

14
A Simple For Loop Example
  • The commands in a for loop are executed for each
    value in the index matrix.
  • for i15
  • xfactorial(i)
  • end
  • What is the value of the variable x in the
    Workspace?
  • After executing the loop, if we call for x, it
    has only one value the value of the index the
    final time through the loop.
  • If all the values shall be saved, use the
    following code
  • for i15
  • y(i)factorial(i)
  • end

15
Creating Matrices With for Loops
  • Now we will fill a vector, element by element
    using a for loop

for n15 fpringf('The value of n is now
d\n',n) vector_1(n)n
vector_2(n)n2 end
  • vector_1 stores the value of n
  • vector_1 1 2 3 4 5
  • vector_2 stores the square of n
  • vector_2 1 4 9 16 25

16
Try This
  • An example

17
The Code
18
Nested Loops
  • One loop can be written inside another loop. The
    inner loop is called a nested loop.
  • One application is a multiplication table

for i 13 for j 13 prod
ij fprintf('d d d \n', i, j,
prod) end end
19
Plotting in 2D
  • Use the plot() command

epsilon10 C_as0.5 r0R/20R R5 rhor/R Ca
_Casbesseli(0,rhoepsilon)/besseli(0,epsilon)
plot(rho,Ca_Cas)
  • This will create a plot
  • of rho vs. Ca_Cas, or dependent
  • vs. independent.

20
Changing the plot
  • A grid can help to interpolate the value of a
    function or a set of data.
  • grid on
  • grid off
  • Adding a title and labels gives more meaning to a
    plot.
  • title('\rho vs. C_A/C_A_s')
  • xlabel('\rho')
  • ylabel('C_A/C_A_s')

\rho is used to input Greek letter ?. Use the
help feature to search for how to input other
special characters (under text properties).
21
Plotting Multiple Curves on a Figure
epsilon10 C_as0.5 r0R/20R R5 rhor/R Ca
_Casbesseli(0,rhoepsilon)/besseli(0,epsilon) ep
silon21 Ca2_Casbesseli(0,rhoepsilon2)/besseli(
0,epsilon2) plot(rho,Ca_Cas,rho,Ca2_Cas)
or plot(rho,Ca_Cas) hold on plot(rho,Ca2_Cas)
22
Changing plot style
  • Plot the data with a red, dash-dot line with red
    stars for points
  • Rescale axis
  • Add in a title
  • Add in x, y labels
  • Add in legends
  • Add in text

plot(rho,Ca_Cas,'r-.') hold on plot(rho,Ca2_Cas)
axis(-0.1,1.1,-0.1,1.1) title('\rho vs.
C_A/C_A_s') xlabel('\rho') ylabel('C_A/C_A_s') leg
end('\epsilon 10','\epsilon
1',2) text(0,0.2,'prepared for CH561')
23
Style reference table
Line type Indicator Marker type Indicator Color Indicator
solid - point . blue b
dotted circle o green g
dash-dot -. x-mark x red r
dashed -- plus cyan c
star magenta m
square s yellow y
diamond d black k
triangle down v
triangle up
triangle left lt
triangle right gt
pentagram p
hexagram h
24
Subplots
  • The subplot() function allows for putting
    multiple graphs in one figure.
  • subplot(m,n,p) divides graphing window into a
    grid of m rows and n columns, where p identifies
    the part of the window where the plot will be
    drawn. These positions are counted from left to
    right along each row.

p 1 p 2
p 3 p 4
25
Examples of Subplots
  • To graph sin(x) and cos(x) on the same figure in
    separate plots

subplot(1,2,1) plot(rho,Ca_Cas) title('C_A_1/C_A
_s') xlabel('\rho') ylabel('C_A_1/C_A_s') subpl
ot(1,2,2) plot(rho,Ca2_Cas,'r-.') title('C_A_2/
C_A_s') xlabel('\rho')
26
Saving Figures
  • There are several ways to save plots created in
    MATLAB
  • Store the MATLAB code for generating the plot in
    an M-file
  • Save the figure as a .fig file, which is MATLABs
    graphics format, or in any other standard graphic
    format.
  • Copy the figure into another document EditgtgtCopy
    Figure.

27
Logarithmic Plots(pg. 155 1 pg. 178 2)
  • MATLAB has three kinds of logarithmic plots
  • semilogx
  • semilogy
  • loglog
  • These plots replace linear scales with
    logarithmic scales.
  • Logarithmic scales are used when a variable
    ranges over many orders of magnitude.

28
Getting help in Matlab
  • Function help
  • Topic help

29
Your Turn!
  • Need an example
Write a Comment
User Comments (0)
About PowerShow.com