Sie sind auf Seite 1von 124

MATLAB Basics The Reference

Durga Lal Shretha


Yunqing Xuan

Part-1

Entering Matrices

Enter an explicit list of elements


A = [10 20 30; 1 2 3; 2 4 8];

Load matrices from external data files


A = load('mymagic.txt'); % you need to create the file before
hand

Generate matrices using built-in functions.


A = magic(4)

Create matrices with your own functions in M-files.


A = myfunction(input1,input2) %

copyright Durga Lal Shrestha

Enter an explicit list of elements

Separate the elements of a row with blanks or commas.


Use a semicolon, ; , to indicate the end of each row.
Surround the entire list of elements with square brackets,
[ ].

copyright Durga Lal Shrestha

Subscripts

Using parenthesis (row,column)


e.g. the element in row I and column j of A = A(i,j)

copyright Durga Lal Shrestha

The colon operator :

To generator vector
Unit steps startvalue:endvalue
Nonunit steps with the given increment
startvalue:stepvalue:endvalue

copyright Durga Lal Shrestha

The colon operator : To select subarrays (portion of


matrix)

copyright Durga Lal Shrestha

Selecting subarrays: Common errors

copyright Durga Lal Shrestha

Generating Matrices

Zeros

Ones

copyright Durga Lal Shrestha

Generating Matrices

rand - uniform random number between 0 and 1

randn normal random number(0,1)

copyright Durga Lal Shrestha

10

Concatenation

Concatenation is the process of joining small matrices to


make bigger ones.
Using []

copyright Durga Lal Shrestha

11

Deleting Rows and Columns

copyright Durga Lal Shrestha

12

Reordering data

copyright Durga Lal Shrestha

13

Changing data

copyright Durga Lal Shrestha

14

Arrays

Scalars: zero dimensional or 1 by 1


S = 2.3

Vector: one dimensional (i.e. n by 1 or 1 by n)


V = [1 4 3 5 6]

Matrix: two dimensional (i.e. m by n)


M = [1 2 3
4 5 6]

Array: N dimensional

copyright Durga Lal Shrestha

15

Multidimensional Array

copyright Durga Lal Shrestha

16

size, length, ndims

copyright Durga Lal Shrestha

17

Matrix Algebra

Addition

Subtraction

Matrix multiplication

Array multiplication

copyright Durga Lal Shrestha

18

Addition

+
A and B must have the same size, unless one of them is
a scalar

copyright Durga Lal Shrestha

19

Subtraction

A and B must have the same size, unless one of them is


a scalar

copyright Durga Lal Shrestha

20

Matrix Multiplication

For nonscalar A and B, the number of columns of A must


equal the number of rows of B.
A scalar can multiply a matrix of any size.

copyright Durga Lal Shrestha

21

Array Multiplication

.*
element-by-element product of the arrays A and B
A and B must have the same size, unless one of them is
a scalar

copyright Durga Lal Shrestha

22

Part 2

23

Expressions

Variables
Numbers
Operators
Functions

copyright Durga Lal Shrestha

24

Numbers

MATLAB uses conventional decimal notation, with an


optional decimal point and leading plus or minus sign, for
numbers.
Scientific notation uses the letter e to specify a power-often scale factor.
Imaginary numbers use either i or j as a suffix.
Some examples of legal numbers are
3
-99
0.0001
9.6397238
1.60210e-20
1i
-3.14159j
3e5i

copyright Durga Lal Shrestha

6.02252e23

25

Functions

MATLAB provides a large number of standard elementary


mathematical functions, including abs, sqrt, exp, and sin.
For a list of the mathematical functions, type
help elfun for Elementary functions (Trigonometric, Exponential,
Complex, and Rounding and remainder)
help specfun for Specialized math functions (e.g. gamma, factor
etc)
help elmat for Elementary matrices and matrix manipulation (e.g.
zeros, size, reshape, magic etc.)

Built-in functions are part of the MATLAB core so they


are very efficient, but the computational details are not
readily accessible (e.g sin, sqrt etc).
Other functions, like gamma and sinh, are implemented
in M-files and you can see the code and even modify it if
you want.
copyright Durga Lal Shrestha

26

Data Types

copyright Durga Lal Shrestha

27

Numeric Types

Numeric data types in MATLAB include signed and


unsigned integers, and single- and double-precision
floating-point numbers.
Integers

copyright Durga Lal Shrestha

28

Floating-Point Numbers

Double-Precision Floating Point


MATLAB default data type
64 bits, large memory and more precision

Single-Precision Floating Point


32 bits, less memory and less precision

copyright Durga Lal Shrestha

29

Complex Numbers

>> x = 2 + 3i
x=
2.0000+3.0000i
>> z = complex(2.1, pi)
z=
2.1000 + 3.1416i
>> zr = real(z)
zr =
2.1000
>> zi = imag(z)
zi =
3.1416

copyright Durga Lal Shrestha

30

Infinity and NaN

Infinity
x = log(0);
>> isinf(x)
ans =

NaN (Not a Number)


MATLAB represents values that are not real or complex numbers
with a special value called NaN
0/0
and inf/inf

copyright Durga Lal Shrestha

31

Display Format for Numeric Values

By default, MATLAB displays numeric output as 5-digit


scaled, fixed-point values.
You can change the way numeric values are displayed to
any of the following:

5-digit scaled fixed point, floating point, or the best of the two
15-digit scaled fixed point, floating point, or the best of the two
A ratio of small integers
Hexadecimal (base 16)
Bank notation

Format short (formatting to 5 digit)


Check the current format setting:
get(0, 'format')
ans =
short

copyright Durga Lal Shrestha

32

Format
x = [4/3 1.2345e-6]
x=
1.3333

0.0000

format short e
x
x=
1.3333e+000
1.2345e-006
format long
x
x=
1.33333333333333
0.00000123450000
copyright Durga Lal Shrestha

33

Logical Types

The logical data type represents a logical true or false


state using the numbers 1 and 0, respectively.
(5 * 10) > 40
ans =
1

Vector of logical
[30 40 50 60 70] > 40
ans =

00111

copyright Durga Lal Shrestha

34

Logical Types

Using Logicals in Conditional Statements


str = 'Hello';
if ~isempty(str) && ischar(str)
sprintf('Input string is ''%s''', str)
end
ans =
Input string is 'Hello'

copyright Durga Lal Shrestha

35

Logical Indexing

copyright Durga Lal Shrestha

36

Part 3

37

Characters and Strings

string refers to an array of Unicode characters.


MATLAB represents each character internally as its
corresponding numeric value.
s = 'Hello'
s=
Hello
whos('s')
Name
Size
s
1x5

copyright Durga Lal Shrestha

Bytes
10

Class
char

Attributes

38

Characters and Strings

Padding.

copyright Durga Lal Shrestha

39

Structure Array

Structures are MATLAB arrays with named data


containers called fields.
The fields of a structure can contain any kind of data.

copyright Durga Lal Shrestha

40

Structure Array

copyright Durga Lal Shrestha

41

Structure Array

strArray = struct('field1',val1,'field2',val2, ...)

copyright Durga Lal Shrestha

42

Cell Arrays

A cell array provides a storage mechanism for dissimilar


kinds of data.

copyright Durga Lal Shrestha

43

Cell Arrays

Use { } for constructing, concatenating and indexing

A = {[1 4 3; 0 5 8; 7 2 9], 'Anne Smith'; 3+7i, -pi:pi/4:pi}


A=
[3x3 double] 'Anne Smith'
[3.0000 + 7.0000i] [1x9 double]

copyright Durga Lal Shrestha

44

Part 4
Data Import and Export

45

Supported Types of Data

Binary data from a MATLAB session


Text data
Graphics files
Audio and audio/video data
spreadsheets
Data from the system clipboard
Information from the internet

copyright Durga Lal Shrestha

46

Binary Data from a MATLAB Session

Save and load command for both ASCII and Mat file

copyright Durga Lal Shrestha

47

Load command

copyright Durga Lal Shrestha

48

Part 5
MATLAB Graphics

49

Matlab Graphics

Plotting Process
Graph Components
Figure Tools
Arranging Graphs Within a Figure
Selecting Plot Types

copyright Durga Lal Shrestha

50

Plotting Process

Use plotting tools to create graphs interactively.


plottools

Use the command interface to enter commands in the


CWD or create plotting programs.
x = 0:0.1:2*pi;
plot(x,sin(x)

copyright Durga Lal Shrestha

51

Graph Components

Figure
Plot
Axis
Data

copyright Durga Lal Shrestha

52

Figure Tools: Figure Palette, Plot Browser and Property Editor

copyright Durga Lal Shrestha

53

Arranging Graphs Within a Figure

copyright Durga Lal Shrestha

54

Selecting Plot Types

copyright Durga Lal Shrestha

55

Basic Plotting Functions

copyright Durga Lal Shrestha

56

Plotting Steps

copyright Durga Lal Shrestha

57

Plotting Multiple Data Sets in One Graph

OR

plot(x,y)
hold on
plot(x,sin(x-0.5),'r')
plot(x,sin(x-0.25),'g')

copyright Durga Lal Shrestha

58

Line Styles and Colors

plot(x,y,'--rs','LineWidth',2,...
'MarkerEdgeColor','k',...
'MarkerFaceColor','g',...
'MarkerSize',10)

copyright Durga Lal Shrestha

59

Contour plots

Twenty contours of the peaks function


3

-1

-2

-3
-3

copyright Durga Lal Shrestha

-2

-1

60

Contour

copyright Durga Lal Shrestha

61

Contour3

Twenty Contours of the peaks Function

10

-5

-10
2
0
-2
-3
copyright Durga Lal Shrestha

-2

-1

62

3D plot

Plot3 command

copyright Durga Lal Shrestha

63

Plotting Matrix Data

copyright Durga Lal Shrestha

64

Plotting Image Data

100

200

300

400

500

600
100

copyright Durga Lal Shrestha

200

300

400

500

65

Surface plot

0.5

-0.5
10
5

10
5

-5

-5
-10

copyright Durga Lal Shrestha

-10

66

Surface plot

copyright Durga Lal Shrestha

67

Creating Stream Particle Animations

copyright Durga Lal Shrestha

68

Part 6
Program components

69

Basic Program Components

Variables
Keywords
Special Values
Operators
MATLAB Expressions
Program Control Statements
Symbol Reference
MATLAB Functions

copyright Durga Lal Shrestha

70

Variables

A MATLAB variable is essentially a tag that you assign to


a value while that value remains in memory.
Local Variables (local to functions)
Global Variables (share a single copy of a variable)
Persistent Variables (retained value from one function call to the
next)

copyright Durga Lal Shrestha

71

Naming Variables

Any combination of characters, numbers and underscore


(starting with characters)
Case sensitive
e.g. Variable1, variable1 are different

MATLAB uses only the first N characters of the name and


ignores the rest, where N = namelengthmax (63)
The genvarname function can be useful in creating
variable names that are both valid and unique.
E.g. four similar variable name strings that do not conflict with
each other: v = genvarname({'A', 'A', 'A', 'A'})
v = 'A' 'A1' 'A2' 'A3'

copyright Durga Lal Shrestha

72

Keywords

MATLAB reserves certain words for its own use as


keywords of the language.
To list the keywords, type iskeyword

'break
'catch
'else
'end
'function
'if
'persistent
'switch
'while'

copyright Durga Lal Shrestha

'case'
'continue'
'elseif'
'for'
'global'
'otherwise'
'return'
'try'

73

Special Values

copyright Durga Lal Shrestha

74

Operators

Arithmetic Operators
Relational Operators
Logical Operators

copyright Durga Lal Shrestha

75

Arithmetic Operators

copyright Durga Lal Shrestha

76

Relational Operators

copyright Durga Lal Shrestha

77

Logical Operators

copyright Durga Lal Shrestha

78

Operator Precedence

Parentheses ()
Transpose (.'), power (.^), complex conjugate transpose (), matrix
power (^)
Unary plus (+), unary minus (-), logical negation (~)
Multiplication (.*), right division (./), left division (.\), matrix
multiplication (*), matrix right division (/), matrix left division (\)
Addition (+), subtraction (-)
Colon operator (:)
Less than (<), less than or equal to (<=), greater than (>), greater
than or equal to (>=), equal to (==), not equal to (~=)
Element-wise AND (&)
Element-wise OR (|)
Short-circuit AND (&&)
Short-circuit OR (||)

copyright Durga Lal Shrestha

79

Scripts and Functions

Scripts
Scripts are the simplest kind of M-file because they have no
input or output arguments.
They are useful for automating series of MATLAB commands.
They operate on data in the workspace.

copyright Durga Lal Shrestha

80

Program Control Statements

Program control is divided into four categories:

Conditional Control if, switch


Loop Control for, while, continue, break
Error Control try, catch
Program Termination return

copyright Durga Lal Shrestha

81

Conditional Control if
if logical_expression

statements
end
if logical_expression1

statements1
elseif logical_expression2
statements2
else

statements3
end

copyright Durga Lal Shrestha

82

Conditional Control switch, case, and otherwise

copyright Durga Lal Shrestha

83

Loop Control for

The for loop executes a statement or group of


statements a predetermined number of times.

for index = start:increment:end

statements
end

copyright Durga Lal Shrestha

84

Loop Control while

The while loop executes a statement or group of


statements repeatedly as long as the controlling
expression is true.

copyright Durga Lal Shrestha

85

Loop Control continue

The continue statement passes control to the next


iteration of the for or while loop in which it appears,
skipping any remaining statements in the body of the
loop.

copyright Durga Lal Shrestha

86

Loop Control break

The break statement terminates the execution of a for


loop or while loop.

copyright Durga Lal Shrestha

87

Error Control- try and catch

Error control statements provide a way for you to take


certain actions in the event of an error.

copyright Durga Lal Shrestha

88

Program Termination return

Program termination control enables you to exit from


your program at some point prior to its normal
termination point.

copyright Durga Lal Shrestha

89

Part 7
Symbol Reference

90

Symbol Reference

At @
for fhandle = @myfun
Colon :
Comma ,
Curly Braces { }
Dot .
Dot-Dot-Dot (Ellipsis) ... on page 3-103
Exclamation Point ! for Shell Escape (e.g. !dir)
Parentheses ( ) for array indexing and function input arguments
Percent % and Percent-Brace %{ %}
Semicolon ;
Single Quotes for character and string
Space Character
Square Brackets [ ]

copyright Durga Lal Shrestha

91

Colon :

Numeric Sequence Range and Step

Indexing Range Specifier

Conversion to Column Vector

Preserving Array Shape on Assignment

copyright Durga Lal Shrestha

92

Comma ,

Row Element Separator

Array Index Separator

Function Input and Output Separator

Command or Statement Separator

copyright Durga Lal Shrestha

93

Curly Braces { }

Cell Array Constructor

Cell Array Indexing

copyright Durga Lal Shrestha

94

Dot .

Structure Field Definition

Object Method Specifier

copyright Durga Lal Shrestha

95

Dot-Dot-Dot (Ellipsis) ...

Line Continuation

Entering Long Strings


You cannot use an ellipsis within single quotes to continue a
string to the next line:

copyright Durga Lal Shrestha

96

Percent % and Percent-Brace %{ %}

Single Line Comments

Conversion Specifiers

Block Comments

copyright Durga Lal Shrestha

97

Semicolon ;

Array Row Separator

Output Suppression

Command or Statement Separator

copyright Durga Lal Shrestha

98

Space Character

Row Element Separator

Function Output Separator

copyright Durga Lal Shrestha

99

Square Brackets [ ]

Array Constructor

Concatenation

Function Declarations and Calls

copyright Durga Lal Shrestha

100

Part 8
M-File Programming

101

Scripts and Functions

There are two kinds of M-files.

Scripts, which do not accept input arguments or return


arguments. They operates on data in the workspace
Functions are M-files that can accept input arguments
and return output arguments.

Functions operate on variables within their own workspace,


separate from the base workspace.
The names of the M-file and of the function should be the same.

copyright Durga Lal Shrestha

102

Scripts: small exercise

Create a file called magicrank.m

copyright Durga Lal Shrestha

103

Functions

Create a file called fmagicrank.m

help fmagicrank
type mr = fmagicrank(10);

copyright Durga Lal Shrestha

104

Basic Parts of an M-File

copyright Durga Lal Shrestha

105

Function Definition Line

function y = fact (x)


input argument
function name
output argument
keyword

copyright Durga Lal Shrestha

106

Creating a Simple M-File

1. Create an M-file using a text


editor.

2. Call the M-file from the


command line or from within
another M-file

copyright Durga Lal Shrestha

function c = myfunc(a,b)
c = sqrt((a.^2)+b.^2))

x = 7.5;
y = 3.342;
z = mufunc(x,y)
z=
8.2109

107

Types of Functions

Primary M-File Functions - the first function in an M-file and


typically contains the main program.
Subfunctions - subroutines to the main function or to define
multiple functions within a single M-file.
Nested Functions - functions defined within another
function. They can help to improve the readability of the program
and to give more flexible access to variables in the M-file.
Anonymous Functions - provide a quick way of making a
function from any MATLAB expression. We can compose anonymous
functions either from within another function or at the MATLAB
command prompt.
Overloaded Functions - useful when you need to create a
function that responds to different types of inputs accordingly.
Private Functions - a way to restrict access to a
function. You can call them only from an M-file function in the
parent directory.

copyright Durga Lal Shrestha

108

Constructing an Anonymous Function

copyright Durga Lal Shrestha

109

Nested Functions

copyright Durga Lal Shrestha

110

Subfunctions

copyright Durga Lal Shrestha

111

Exercise Function
function [Y] = filterdata(data,thres)
[NRow,NCol]=size(data);
j=1;
Y=[];
for i=1:NRow
if data(i)>=thres
Y(j)=data(i);
j=j+1;
end;
end;

copyright Durga Lal Shrestha

112

Function Handles

A function handle is a MATLAB value that provides a


means of calling a function indirectly
Construct a function handle in MATLAB using the at sign,
@, before the function name.
fhandle = @sin;

You can call a function by means of its handle in the


same way that you would call the function using its
name.
The syntax is fhandle(arg1, arg2, ...);
fhandle(0.50)

copyright Durga Lal Shrestha

113

Function Functions

One function works on another functions

Zero finding
Optimization
Quadrature
Ordinary differential equations

copyright Durga Lal Shrestha

114

Humps function

copyright Durga Lal Shrestha

115

hold on;
plot(p,humps(p),'r*');

copyright Durga Lal Shrestha

116

copyright Durga Lal Shrestha

117

Q = quadl(@humps,0,1)
Q=
29.8583

Z = fzero(@humps,0.5)
Z=
-0.1315

Z = fzero(@humps,1)
Z=
1.2955

f = humps(Z)
f=
0

copyright Durga Lal Shrestha

118

Part 9: GUIDE
Simple Graphical User Interface

119

GUIDE

GUIDE, the MATLAB graphical user interface


development environment, provides a set of tools for
creating graphical user interfaces (GUIs).

copyright Durga Lal Shrestha

120

Simple gui example

copyright Durga Lal Shrestha

121

Simple gui example

copyright Durga Lal Shrestha

122

Simple gui example

copyright Durga Lal Shrestha

123

Simple gui example

copyright Durga Lal Shrestha

124

Das könnte Ihnen auch gefallen