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

Introduction

to MATLAB

2017.02. 송지원
01 Introduction

CONTENTS 1
2
What is MATLAB?
Getting started
3 Editor
4 MATLAB Help

02 MATLAB Basics
1 What are matrices?
2 Vectors and matrices
3 Colon operator
4 Vector and matrix indexing
5 Deleting rows and columns

03 Basic data types and Operations


1 Basic data types
2 Variable names
3 Arithmetic operators
4 Relational operators
5 Logical operators
04 MATLAB functions
CONTENTS 1 M-file
2 Simple built-in functions
3 Defining a function

05 Programming in MATLAB
1 If statement
2 Switch statement
3 For loop
4 While loop

06 Plotting
1 Plot
2 Color, style and marker
3 Multiple plots
4 Subplots
01
Introduction 1 What is MATLAB?

The name MATLAB stands for “MATrix LABoratory” and Typical


areas of use include:

• Math and Computation

• Modeling and Simulation

• Data Analysis and Visualization

• Application Development

• Graphical User Interface Development


01
Introduction 2 Getting Started

• Command Window: Run MATLAB statements.


• Current Directory: To view, open, search for, and make changes to MATLAB related directories
and files.
• Command History: Displays a log of the functions you have entered in the Command Window.
You can copy them, execute them, and more.
• Workspace: Shows the name of each variable, its value, and the Min and Max entry
if the variable is a matrix.
01
Introduction 3 Editor

• The MATLAB editor can be used to create and edit M–files, in which you can write and save
MATLAB programs.
• A m-file can take the form of a script file or a function.
• A script file contains a sequence of MATLAB statements; the statements contained in a script file
can be run in the specified order, in the MATLAB command window simply by typing the name of
the file at the command prompt
Workspace
Current Directory Editor

Command Window Command History


Figure1.
MATLAB Desktop
(default layout)
01
Introduction 4 MATLAB Help

• HELP: “help plot” displays a description of and syntax for the function plot in the Command
Window
• DOC: “doc plot” displays the help browser for the MATLAB function plot. You can invoke the
MATLAB help browser by typing ”helpbrowser” at the MATLAB command prompt, clicking on the
help button, or by selecting Start → MATLAB → Help from the MATLAB desktop.
02
MATLAB Basics 1 What are matrices?

• Array: a set of sequentially indexed elements


• Matrices: a rectangular array of mathematical elements
02
MATLAB Basics 1 What are matrices?

▷ Scalars, vectors, matrices

• 3 variables: a, B and C
• a is a scalar: one-‐ dimensional array with one element
• B is a vector: one-‐ dimensional array with length 7
• C is a matrix: a two-‐dimensional array
• Scalars, vectors and matrices are all arrays
• MATLAB prefers operations on arrays instead of scalars
02
MATLAB Basics 2 Vectors and matrices

• The examples below illustrate how vectors and matrices can be created in MATLAB .

▷ a row vector A ▷ a column vector B ▷ a matrix C


>> A = [1, 2, 3] >> B = [4; 5; 6] >> C = [1 2 3; 4 5 6]
A = B = C =
1 2 3 4 1 2 3
5 4 5 6
6
02
MATLAB Basics 2 Vectors and matrices

▷ Simple matrices : ones, zeros, eye, diag

• ex

>> A = ones(2) >> B = zeros(2,3) >> C = eye(3) >> D = diag([1, 2, 3])


C = B = C = D =
1 1 0 0 0 1 0 0 1 0 0
1 1 0 0 0 0 1 0 0 2 0
0 0 1 0 0 3
02
MATLAB Basics 2 Vectors and matrices

▷ Concatenating matrices

• Concatenating matrices are straightforward MATLAB as long as their dimensions are consistent
• ex
>> A = [1, 2, 3]; B = [4, 5, 6];
>> C = [A, B]
C =
1 2 3 4 5 6
>> C = [A; B]
C =
1 2 3
4 5 6
02
MATLAB Basics 3 Colon operator

• The colon operator( : ) allows you to create vectors with a sequence of values from the
start value to the stop value with a specified increment value

• ex >> A = [-2: 2]
A =
-2 -1 0 1 2

>> A = [2: -1: -2]


A =
2 1 0 -1 -2
02
MATLAB Basics 3 Colon operators

• The colon operator can also be used to access the whole or a set consecutive elements within
a dimension of a matrix.
• ex >> C = [1 2 3; 4 5 6; 7 8 9]
C =
1 2 3
4 5 6
7 8 9
>> C( :,3 ) >> C( 2:3, 2:3 )
ans = ans =
3 5 6
6 8 9
9
02
MATLAB Basics 4 Vector and matrix indexing

>> A = [1 2 3;4 5 6;7 8 9;10 11 12]


A =
1 2 3
4 5 6
7 8 9
10 11 12

• The element on the 3rd row of the 2nd column


can be accessed like:
>> A(3, 2) >> A(7)
ans = ans =
8 8
02
MATLAB Basics 4 Vector and matrix indexing

▷ Higher – order arrays


• ex A(2,4,3) = element in a 3‐dimensional array
02
MATLAB Basics 5 Deleting rows and columns

• You can delete rows and columns from a matrix


• A = [1 2 3; 4 5 6; 7 8 9];
– Delete second row
A(2,:) = [];

• You cannot delete single elements


– A(2,2) = []; %will not work and why should it?

• But if you delete a subscript, the remaining elements will become a row vector
– A(1) = []; %will work
03
Basic data types and Operations 1 Basic data types

• 15 Fundamental data types


– Each is an array/matrix of minimum 0x0 and can grow dynamically

• Default numeric type is double


• Most used types
– Logical: true/false
– Char: array of characters
– Double: array of doubles

single(x)
03
Basic data types and Operations 1 Basic data types

▷ Cells and Structures

• Cells : Array of indexed cells, each capable of storing array of different dimension and data type

• ex a{1,1} = 12; a{1,2} = 'Red'; a{1,3} = magic(4);

• Structure : C-‐like structure, named fields capable of storing array of different dimension and
data type

• ex a.number= 12; a.color= 'Red'; a.mat= magic(3);


03
Basic data types and Operations 2 Variable names

▷ Some specific rules for naming variables

• Only use primary alphabetic characters (i.e., ”A-Z”), numbers, and the underscore character in
variable names.
• No spaces in variable names.
• MATLAB is case sensitive. The same text, with different combinations of capital and small case
letters, will not be interpreted the same in MATLAB .
For example, ”VaRIAbLe”, ”variable”, ”VARIABLE” and ”variablE” would all be considered distinct
variables in MATLAB .
03
Basic data types and Operations 3 Arithmetic operators


+ Addition

- Subtraction

* Multiplication

/ Division

\ Left division

^ Power

’ Complex conjugate transpose

• Examples x + y/ x * y/ x^2
03
Basic data types and Operations 4 Relational operators


< Less than

<= Less than or equal to

> Greater than

>= Greater than or equal to

== Equal to

~= Not equal to

• Examples x < y / A == B/
04
MATLAB Functions 1 M-files

• You can create M-files (the file extension .m).


• These can be either scripts or functions.

• Scripts work like an extended command line statement. All variables are shared between the
workspace and the script. Scripts have no input or output arguments.
• Functions have their own workspace. They are usually called with one or several input
arguments and return one or several output arguments. They are declared by the keyword
function.
04
MATLAB Functions 2 Simple Built-in Functions

• Trigonometric functions: sin, cos, tan, asin, acos, atan


• Exponential: exp, log, log2, log10
• Random number generator: rand, randn, randperm, mvnrnd
• Data analysis: min, max, mean, median, std, var, cov
• Linear algebra: norm, det, rank, inv, eig, svd, null, pinv
• Strings: strcmp, strcat, strfind, sprintf, sscanf, eval
• Files: save, load, csvwrite, csvread, fopen, fprintf, fscanf
• Other: abs, sign, sum, prod, sqrt, floor, ceil, round, sort, find
• Master key: help, doc, and Google the external function!
04
MATLAB Functions 3 Defining a function

• The general form of a function declaration


function [return_args] = function_name(input_args)
function body ...
• ex function p = product(a,b)

p = a*b;

Saved under the file name product.m. It can be called from the command line.

>> x = product(3,4)
x =
12
05
Programming in MATLAB 1 If statement

• The syntax of if, else and elseif

if condition if condition if condition 1


statement 1 statement 1 statement 1
statement 2 else elseif condition 2
∙∙∙ statement 2 statement 2
statement n end elseif condition 3
end statement3
end
05
Programming in MATLAB 2 Switch statement

• The syntax of switch statement


switch condition
case condition 1
statements 1
case condition 2
statements 2
...
otherwise
statements n
end
05
Programming in MATLAB 2 Switch statement

• ex grade = 'B';
switch(grade)
case 'A'
fprintf('Excellent!\n' );
case 'B'
fprintf('Well done\n' );
case 'C'
fprintf(‘You passed\n' );
otherwise
fprintf('Invalid grade\n' );
end
05
Programming in MATLAB 3 For loop

• Repeats a group of statements a fixed, predetermined number of times

• Syntax
for variable = vector
statements
end
05
Programming in MATLAB 3 For loop

• ex for ii = 1:10

for jj = 1:10

A(ii,jj) = ii / jj;

end

end
05
Programming in MATLAB 4 While loop

• Repeat a group of statements an indefinite number of times under control of


a logical condition

• Syntax
while condition
statements
end
05
Programming in MATLAB 3 While loop

• ex ii = 1;

while ii < 10000

A(ii) = ii/10000;

ii = ii + 1;

end
06
Plotting 1 Plot

▷ plot
• The most basic plotting command is plot !
– plotting the values of a vector versus the index of the elements : plot(y)
– plotting the values of a vector versus the values of another vector : plot(x,y)

• ex >> x = 0:pi/100:2*pi;
>> y = sin(x);
>> plot(x,y)
06
Plotting 1 Plot

• More about plot


- It is possible to label the axis on a graph with xlabel and ylabel commands

• ex >>xlabel(‘x’)

>>ylabel(‘y=cos(x)’)

You could even put a title on top

>> title('Graph of cosine from -pi to pi')


06
Plotting 2 Color, style and marker

• It is possible to specify color, line styles, and markers when you plot your data using the plot
command: plot(x,y,’color_style_marker’)


Type Values Meanings
Color ‘r’ red
‘g’ green
‘b’ blue
Line style ‘-’ solid
‘- -’ dashed
‘:’ dotted
Marker ‘+’ plus mark
‘s’ filled square
06
Plotting 3 Multiple plot

1) plot(x1, y1, ‘linespec1’, x2, y2, ‘linespec2’,∙∙∙, xn, yn, ‘linespec’)


• ex >> x = 0 : 0.2 : 10;
>> y1 = cos(x);
>> y2 = sin(x);
>> plot (x, y1, ‘b-o’, x, y2, ‘r--‘)
2) Use hold on command
• ex >> x = 0:pi/100:2*pi;
>> y = sin(x);
>> plot(x,y);
>> hold on
>> y2= 2 + sin(x);
>> plot(x, y2, ‘m:’)
>> hold off
06
Plotting 4 Subplots

• subplot (M, N, P)

: There will be M rows and N columns of subfigures and MATLAB will place the result of the
next ”plot” command in the Pth subfigure

• ex >> X = [1 3 4 6 8 12 18];
>> Y1 = 3*X;
>> Y2 = 4*X+5;
>> subplot(2,1,1)
>> plot(X,Y1)
>> subplot(2,1,2)
>> plot(X,Y2)

You might also like