• 검색 결과가 없습니다.

강의자료실 - 강의자료실

N/A
N/A
Protected

Academic year: 2021

Share "강의자료실 - 강의자료실"

Copied!
14
0
0

로드 중.... (전체 텍스트 보기)

전체 글

(1)

Matlab 의 기본 사용법

http://www.mathworks.com

MATLAB installation

http://itc.chosun.ac.kr

Matlab 기본사용법 2 IML, Chosun MATLAB 입문 Matlab 기본사용법 3

• Introduction

• Matlab 실행

• 실 수, Format, 문자열

• Vector, Matrix

• colon( : ) 연산자, 수 열

• 순환문 - For & While

• M-file (script file, function file)

• eval, disp , sprintf

IML, Chosun

MATLAB 입문

Matlab 기본사용법 4

Introduction

Matlab의 개요

– Cleve Moler에 의해 Fortran으로 작성,

– 현재는 미국의 MathWorks사에 의해 C++

– Matlab 코딩 체계 : 수학적인 기호, C문법

– Matlab :

MAT

rix

LAB

oratory

활용 범위

– 수학과 관련된 계산

– 알고리즘 개발

– 상황 모델링과 data분석

– 여러 가지 과학과 공학적인 그래픽적 표현

– GUI(Graphical User Interface)에 의한 에플리케이션 개발.

IML, Chosun MATLAB 입문 Matlab 기본사용법 5

Matlab은 기본적으로 행렬을 자료로 다룬다.

-> dimensioning이 필요하지 않으며

통상적인 프로그램 언어들을 사용하여 프로그램을

작성하지 않고도 쉽게 수치 계산을 수행할 수 있다.

Matlab의 toolbox

: 신호 처리, 통계학, 영상 처리, 제어, fuzzy logic, 재정,

화학 공정, 해당 전공 부분의 내용을 지원하는 함수들의 모임

Matlab은 외부 프로그램, ( C or Fortran programming)과

link해서 이용할 수 있는 기능도 제공한다.

Matlab 실행

IML, Chosun MATLAB 입문 Matlab 기본사용법 6

Execution Screen

(2)

Matlab 기본사용법 7

왜 Matlab을 배워야 하는가?

Matlab에서 위의 문제는

>> y=quad('sin(x)', 0, pi/2)

>> syms x, int(sin(x))

Matlab은 강력한 수학적인 능력을 갖고 있고,

또한, 쉽게 주어진 상황을 코딩화할 수 있다.

dx

x

y

dx

x

y

sin

sin

0

symbolic computation Matlab 기본사용법 8

주석문 : ‘

%

’를 붙인다.

수식 표현 뒤에 ‘

;

’ 오면 결과값이 출력 안됨

할당(assign, substitute)

variable

=

expression

(variable : 변수, 타 language 변수와 유사

expression : 값, vector, 행렬 etc. )

편리한 기능키

Tab

: 함수의 전체 이름이 기억 나지 않을 때 함수를 찾아준다.

Ctrl-U

: 현재의 명령을 삭제

Ctrl-C, Esc

: 현재 계산중인 명령을 중단(Esc와 같음)

up-arrow key(

) & down-arrow key(

): move up and down through the previously typed

lines one line at a time.

MATLAB 계산

IML, Chosun

MATLAB 입문

Matlab 기본사용법 9

MATLAB Help functions (help, lookfor, doc)

lookfor

: find functions that are relevant to your application

help

: when you know the correct spelling of the function

IML, Chosun

MATLAB 입문

Matlab 기본사용법 10

규칙

주석 또는 예

변수들의 이름은

대소문자를 구별

한다

Cost, cost, CoSt, COST 모두다 다른 매

트랩 변수이다.

최대

31개

의 문자를 포함하고 그 이상은

무시된다.

Howaboutthisvariablename

변수 이름은

글자(letter)로 시작

하여야

하고 다른 글자나 숫자, 밑줄긋기( " _ " )

등 올 수 있다. 다른 구두점들은 사용 할

수 없다. ( " , ', . , :, ;, &,% @,# 등등 )

w_about_this_variable_name

x51483

a_b_c_d_e

Reserved Word List

for,end,if,while,function,return,elseif,

case,otherwise,switch,continue,else,try,

catch,global,persistent,break

변수명 규칙

IML, Chosun MATLAB 입문 Matlab 기본사용법 11 특별 변수 설 명 ans 결과를 항상 나타내는 임시변수 beep 컴퓨터에서 소리발생 명령 pi 원주와 지름의 비율, 즉 π eps 매트랩에서 다루어질 수 있는 절대값이 가장 작은 수( 0 뻬고) Inf 무한을 뜻한다. 예) 1/0 NaN 숫자가 아님을 나타낸다. 예 ) 0/0 i or j 복소수 i를 뜻한다. 예) 3 + 4i, 5+ 6j nargin 함수에 입력변수(argument)의 개수 nargout 함수에서 출력변수(argument)의 개수

varargin an input variable in a function to accept any number of input arguments

varargout an output variable in a function to return any number of output arguments

특별변수

IML, Chosun MATLAB 입문 Matlab 기본사용법 12

Format

format

short

( long, short e, long e, rat, hex )

pi

format short 3.1416

format long 3.14159265358979 (16자리)

format short e 3.1416e+000 (base는 10)

format long e

3.141592653589793e+000

format rat

355/113 (근사값에 가장 가까운 분수)

(3)

Matlab 기본사용법 13

Matlab 연산

>> a = 3. 5 ;

>> b = 5.7 ;

>> a+b

9.2000

>> a - b

>> a * b

>> a / b

>> a^2

>> sqrt(a)

참고 : 허수는 i 혹은 j을 사용  3+2*i

+

더하기 (addition)

/

오른 나누기 (right division)

-

(substractio빼기 n) \→₩ 왼 나누기 (left division)

*

(multiplicati곱하기 on)

^

거듭제곱 (power) 수식의 계산에 사용되는 산술 연산자들은 일 반적으로 사용되는 것들과 같으며, 연산의 우 선 순위도 동일함.

문자열

Matlab 기본사용법 14

문자열을 입력하고자 할 때에는 원하는 문자열의 전후

에 작은따옴표(')를 붙이면 된다.

Ascii코드

행벡터

>> s='MATLAB'

s =

MATLAB

>> size(s)

ans =

1 6

>> abs(s)

ans =

77 65 84 76 65 66

IML, Chosun MATLAB 입문 15

Arrays

Arrays

: Collection of numbers

the basic building block in MATLAB

addition, subtraction, multiplication, division, and exponentiation

polynomial algebra and root

Available classes of arrays in MATLAB 7

numeric

arrays : contains only numeric values

cell

arrays : access data by its location

structure

arrays : access data by name

Array

numeric character logical

cell

structure

function

handle

Java

IML, Chosun

MATLAB 입문

16

Arrays

Cartesian coordinates x, y, and z

unit vector

i, j, k

express the vector p = xi + yj + zk

e.g.

p = 5i + 7j + 2k

in MATLAB: write in a specific order,

separate with a space,

identify the group with brackets

[5 7 2]

vector

row

vector

[5 7 2]

column

vector

IML, Chosun MATLAB 입문 17

Arrays

Creating Vectors in MATLAB

MATLAB displays row vectors horizontally and column vectors vertically.

Create a row vector : space or commas separate elements

g = [3 7 9] = [3,7,9]

Create a column vector : semicolon or Enter separate elements, you can use

transpose

g = [3;7;9] = [3,7,9]’ = [3

(Enter)

7

(Enter)

9]

Create vectors by “appending”

r = [2, 4, 20], w = [9, -6, 3]

u = [r, w] = [2, 4, 20, 9, -6, 3]

IML, Chosun MATLAB 입문 18

Arrays

Creating Vectors in MATLAB

Generate a large vector of regularly spaced elements using colon operator (:)

x = [m:q:n]

m : the first value q : the increment (default = 1) n : the last value <= n

x = [0:2:8] = [0, 2, 4, 6, 8]

x = [0:2:7] = [0, 2, 4, 6]

y = [-3:2] = [-3, -2, -1, 0, 1, 2]

u = [10:-2:4] = [10, 8, 6, 4]

The

linspace

command,

logspace

command

linspace(x1, x2, n) : n is number of points between x1 and x2

linspace(5,8,31) = [5:0.1:8]

logspace(a, b, n) : n is number of points between 10

a

and 10

b logspace(-1,1,4) = [0.1000, 0.4642, 2.1544, 10.000]

(4)

19

Arrays

Two-Dimensional Arrays

 An array can have multiple rows, multiple columns, or both  called a matrix

 . 

Creating Matrices

 Space or commas separate elements in different columns  Semicolons separate elements in different rows  You can also create a matrix from row or column vectors <example (a = [1,3,5], b=[7,9,11]) >        7 3 16 10 4 2 M [1, 3, 5; 7, 9, 11] [a; b] [a b]       11 9 7 5 3 1

1 3 5 7 9 11

20

Arrays

Array Addressing

The row number is always listed first

The colon operator selects individual elements, rows, columns, or ”subarrays” of arrays

 v( : ) represents all the row or column elements of the vector v.

 v(2 : 5) represents the second through fifth elements

 A( : , 3) denotes all the elements in the third column of the matrix A

C = B(2:3, 1:3)

9

4

8

7

3

16

C

17

15

12

3

25

9

4

8

18

7

3

16

13

10

4

2

B

IML, Chosun MATLAB 입문 21

Arrays

The empty or null array

 contains no elements, [ ]

 Rows and columns can be deleted by setting the selected row or column equal to the null array.

A(3, :) = [ ] deletes the third row in A

A(:, 2:4) = [ ] deletes the second through fourth columns In A

A([1 4], : ) = [ ] deletes the first and fourth rows of A

< Other examples >

7

5

1

4

9

6

A

A(1,5) = 3

0

0

7

5

1

3

0

4

9

6

A

B = A(:,5:-1:1)

1

5

7

0

0

6

9

4

0

3

B

IML, Chosun MATLAB 입문 22

Arrays

Magnitude, Length, and Absolute Value of a Vector

length : the number of elements in the vector.magnitude :

absolute value : The absolute value of a vector x is a vector whose elements are the absolute values of the elements of x.

<example> x = [2, -4, 5]

length = 3, magnitude = 6.7082, absolute value = [2, 4, 5]

The Array Editor

A graphical interface for working with arrays.

To open the Array Editor from the Workspace Browser, double-click on the variable you want to open.

2 2 2 2 1 x xn x   IML, Chosun MATLAB 입문 23

Multidimensional Arrays

MATLAB supports multidimensional arrays

The first two dimensions are the row and column, as with a matrix.

The higher dimensions are called pages.

<example>

Want to create a three dimensional array whose first page is

and whose second page is

>>A = [4, 6, 1;5, 8, 0;3, 9, 2]; >>A( : , : , 2) = [6, 2, 9;0, 3, 1;4, 7, 5];catcommand           2 9 3 0 8 5 1 6 4           5 7 4 1 3 0 9 2 6        5 9 2 8 A        3 7 6 4

B C = cat(3, A, B) produces a three-dimensional array

IML, Chosun

MATLAB 입문

24

Element-by-Element Operations

Element-by-element operations

Symbol Operation Form Example

+ Scalar-array addition A + b [6, 3] + 2 = [8 ,5] - Scalar-array subtraction A – b [8, 3] - 5 = [3, -2] + Array addition A + B [6, 5] + [4, 8] = [10, 13] - Array subtraction A – B [6, 5] - [4, 8] = [2, -3] .* Array multiplication A.*B [3, 5] .* [4, 8] = [12, 40] ./ Array right division A./B [2, 5] ./ [4, 8] = [2/4, 5/8] .\ Array left division A.\B [2, 5] .\ [4, 8] = [2\4, 5\8] .^ Array exponentiation A.^B [3, 5] .^2 = [3^2, 5^2]

2 .^ [3, 5] = [2^3, 2^5] [3, 5] .^ [2, 4] = [3^2, 5^4]

(5)

25

Matrix Operations

Matrix Multiplication

Use the operator * to perform matrix multiplication in MATLAB

<example> >>A = [6, -2,;10,3;4,7]; >>B = [9,8;-5,12]; >>A*B ans = 64 24 75 116 1 116 

Special Matrices

Command Description eye(n) Creates an n×nidentity matrix.

eye(size(A)) Creates an identity matrix the same size as the matrix A. ones(n) Creates an n×nmatrix of ones.

ones(m,n) Creates an m×narray of ones.

ones(size(A)) Creates an array of ones the same size as the array A. zeros(n) Creates an n×nmatrix of zeros.

zeros(m,n) Creates an m×narray of zeros.

zeros(size(A)) Creates an array of zeros the same size as the array A.

26

Matrix Operations

Matrix Division

 Right and left operators, / and \

 Chapter 6 covers matrix division and matrix inverse.

Matrix Exponentiation

 must be a square matrix  to find A2,type A^2 

Special products

Command Syntax

cross(A, B) Computes a 3×n array whose columns are the cross products of the corresponding columns in the 3×n arrays A and B. Returns a three-element cross-product vector if A and B are three-three-element vectors. dot(A, B) Computes a row vector of length n whose elements are the dot

products of the corresponding columns of the m×n arrays A and B

IML, Chosun

MATLAB 입문

27

Polynomial Operations Using Arrays

Type

help polyfun

for more information

We will use following notation

Polynomial Addition and Subtrction

 add the arrays that describe their coefficients

 if the polynomials are of different degrees, add zeros to the coefficient array of the leower-degree polynomial.

<example>

coefficient array is f=[9, -5, 3, 7] and g = [6, -1, 2] g = [0 g] = [0, 6, -1, 2] h = f+g = [9, 1, 2, 9] 1 2 1 2 3 1 2 1 ) (     n nnn n n ax ax a x ax a x a x f  7 3 5 9 ) (xx3x2x f g(x)6x2x2 h(x)f(x)g(x) 9 2 9 ) (xx3x2x h IML, Chosun MATLAB 입문 28

Polynomial Operations Using Arrays

Polynomial Multiplication and Division

 Multiply polynomials : use conv function (it stands for “convolve”)  synthetic division : use deconv function (it stands for “deconvolve”)

Polynomial functions

Command Description

conv(a, b) Computes the product of the two polynomials described by the coefficient arrays a and b.

[q, r] = deconv(num, den)

Computes the result of dividing a numerator polynomial, whose coefficient array is num, by a denominator polynomial represented by the coefficient array den. The quotient polynomial is given by the coefficient array q, and the remainder polynomial is given by the coefficient array r.

poly(r) Computes the coefficients of the polynimial whose roots are specfied by the vector r.

polyval(a, x) Evaluates a polynomial at specified values of its independent variable x, which can be a matrix or a vector. The polynomial’s coefficients of descending powers are stored in the array a. The result is the same size as x.

roots(a) Computes the roots of a polynomial specified by the coefficient array a. The result is a column vector that contains the polynomial’s roots.

14 29 41 39 54 ) 2 6 )( 7 3 5 9 ( ) ( ) ( 2 3 4 5 2 2 3             x x x x x x x x x x x g x f 5833 . 0 5 . 1 2 6 7 3 5 9 ) ( ) ( 2 2 3         x x x x x x x g x f >>f = [9, -5, 3, 7]; >>g = [6, -1, 2]; >>product = conv(f, g) product = 54 -39 41 29 -1 14 >>quotient, remainder] = deconv(f,g) quotient = 1.5 -0.5833 remainder = 0 0 -0.5833 8.1667 IML, Chosun MATLAB 입문 29

Polynomial Operations Using Arrays

Plotting Polynomials

 The polyval(a,x) function is very useful for poltting polynomials.

<example>

plot the polynomial

7

3

5

9

)

(

3

2

x

x

x

x

f

for

2

x

5

-2 -1 0 1 2 3 4 5 -200 0 200 400 600 800 1000 1200 x f( x) IML, Chosun MATLAB 입문 30

Some Useful Array Functions

Command Description

cat(n, A, B, C, …) Creates a new array by concatenating the arrays A, B, C, and so on along the dimension n.

find(x) Computes an array containing the indices of the nonzero elements of the array x.

[u, v, w] = find(A) Computes the arrays u and v, containing the row and column indices of the nonzero elements of the matrix A, and the array w, containing the values of the nonzero elements. The array w may be omitted. 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

×n matrix.

linspace(a,b,n) Creates a row vector of n regularly spaced values between a and b

logspace(a,b,n) Creates a row vector of n logarithmically spaced values between a and b

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. If any of the elements are complex, max(A)returns the elements that have the largest magnitudes.

[x, k] = max(A) Similar to max(A)but stores the maximum values in the row vector x and their indices in the row vector k

min(A) Same as max(A)but returns minimum values. [x, k] = min(A) Same as [x, k] =max(A)but returns minimum values. size(A) Returns a row vector [m n] containing the sizes of the m × n array A.

sort(A) Sorts each column of the array A in ascending order and returns an array the same size as A.

(6)

Matlab 기본사용법 31

FOR loop

>> for k=1:20, y(k)=k^2; end, y

forloop variable(k) = beginning number(m) : step increment(s): last number(n) statements

end

>> x=0 :

0.1

: 2*pi ;

>> n=length(x)

>> for k=1:n, y(k)=sin(x(k)); end

>> plot(x, y)

Matlab 기본사용법 32

n! 의 계산

10! 의 값은 ?

n!= n*(n-1)* … *3*2*1

>> m=1

>> for k=10:-1:1

m=m*k ;

end

>> m

IML, Chosun MATLAB 입문 Matlab 기본사용법 33

실 습 – 수열 만들기

다음의 수열을 만들어 보세요

100 95 90 . . . - 95 - 100

2

4 8 16 32 64 128

–1 1 –1 1 –1 1

>> for k=1:7

y(k)=(-1)^k;

end

IML, Chosun MATLAB 입문 Matlab 기본사용법 34

WHILE loop

• 조건이 만족하는 한 실행문장들을 반복 실행.

• 조건이 거짓( 0 이면) 이 될 때까지 수행한다.

while (

조건식

)

statements

end

>> i=1;

>> while

i<=5

x(i)=i*2;

i=i+1;

end

x

Q. for 를 이용하여 문장을 변형하여라.

>> i=1;while i<=5,x(i)=i*2;i=i+1;end,x

IML, Chosun MATLAB 입문 Matlab 기본사용법 35

Mathematical Functions

Function

MATLAB syntax

(◈)

exp(x)

sqrt(x)

log(x)

log10(x)

cos(x)

sin(x)

tan(x)

acos(x)

asin(x)

atan(x)

x

e

x

x

ln

x

log

10

x

cos

x

sin

x

tan

x

cos

-1

x

sin

-1

x

tan

-1

• Some commonly used mathematical

functions

◈The MATLAB trigonometric functions use radian measure

IML, Chosun

MATLAB 입문

36

Numeric Functions

MATLAB

has been optimized to deal with arrays.

round(y)

: rounds to the nearest integer  ans = 2, 3, 4

fix(y)

: truncates to the nearest integer toward zero  ans = 2, 2, 3

ceil(y)

: rounds to the nearest integer toward ∞  ans = 3, 3, 4

e.g.

z = [-2.6 , -2.3 , 5.7]

floor(z)

: rounds to the nearest integer toward - ∞  ans = -3, -3, 5

fix(z) = -2, -2, 5

abs(z) = 2.6 , 2.3, 5.7

(7)

37

Trigonometric Functions

Trigonometric

*angle : radian

cos(x)

Cosine; cos x.

cot(x)

Cotangent; cot x.

csc(x)

Cosecant; csc x.

sec(x)

Secant; sec x.

sin(x)

Sine; sin x.

tan(x)

Tangent; tan x.

Inverse

trigonometric

acos(x)

Inverse cosine;

arccos x =

acot(x)

Inverse cotangent;

arccot x =

acsc(x)

Inverse cosecant;

arccsc x =

asec(x)

Inverse secant;

arcsec x =

asin(x)

Inverse sine; arcsin x

=

atan(x)

Inverse tangent;

arctan x =

atan2(y,x)

four-quadrant

inverse tangent.

x

cos

1

x

cot

1 x csc1 x sec1

x

sin

1 x tan1 38

Hyperbolic Functions(1/2)

Hyperbolic functions

Hyperbolic

cosh(x)

Hyperbolic cosine; cosh x =

coth(x)

Hyperbolic cotangent; cosh x / sinh x

csch(x)

Hyperbolic cosecant; 1 / sinh x

sech(x)

Hyperbolic secant; 1 / cosh x

sinh(x)

Hyperbolic sine; sinh x =

tanh(x)

Hyperbolic tangent; sinh x / cosh x

)/2

e

(e

x

x

)/2

e

(e

x

x IML, Chosun MATLAB 입문 39

Hyperbolic Functions(2/2)

Hyperbolic functions

Inverse hyperbolic

acosh (x)

Inverse hyperbolic cosine;

acoth (x)

Inverse hyperbolic cotangent;

acsch (x)

Inverse hyperbolic cosecant;

asech (x)

Inverse hyperbolic secant;

asinh (x)

Inverse hyperbolic sine;

atanh (x)

Inverse hyperbolic tangent;

1

x

),

1

x

ln(x

x

cosh

1

2

1 2 1    ), x 1 x 1 -x 1 x ln( x coth1 or 0 x ), 1 x 1 x 1 ln( x csch1   2   1 x 0 ), 1 x1 x 1 ln( x sech1   2          x ln(x x 1), - x sinh1 2 1 x 1 ), x -1x 1 ln( 2 1 x tanh1 IML, Chosun MATLAB 입문 Matlab 기본사용법 40

Working with Files

M-file

: MATLAB function files and program files are saved with the

extension .m, and called M-files.

MAT-file

: save the names and values of variables .

ASCII-file

: files written in a specific format designed to make them

usable to a wide variety of software.

system, directory, and file commands

addpathdirname Adds the directorydirnameto the search path. cd dirname Changes the current directory to dirname. dir Lists all files in the current directory. dir dirname Lists all the files in the directory dirname. path Displays the MATLAB search path. pathtool Starts the Set Path tool. pwd Displays the current directory.

rmpath dirname Removes the directory dirnamefrom the search path.

what Lists the MATLAB-specific files found in the current working directory. Most data files and other non-MATLAB files are not listed. Use dirto get a list of all files. what dirname Lists the MATLAB-specific files in directory dirname.

IML, Chosun

MATLAB 입문

Matlab 기본사용법 41

Script Files and the Editor/Debugger

Two ways for performing operations in MATLAB

Interactive mode

:directly enter the commands in the Command window  usingscriptfiles (commandsfiles)

:store the commands in script files

M-files

scriptfiles

:when need to use many commands or arrays with many elements  functionfiles

:when need to repeat the operation of a set of commands

M-file 생성 및 저장

IML, Chosun

MATLAB 입문

42

User-Defined Functions(1/4)

Function file

: when need to repeat a set of commands several times.

variables : local

syntax

function [output variables] = function_name (input variables)

function_name

= saved file name

( with the .m extension)

 function_name

= drop : file name = drop.m

(8)

MATLAB 입문

43

User-Defined Functions(2/4)

e.g.

Local variables

 variables created by a function file arelocalto that function.  local: their values are not available outside the function.

Global variables

 their values are available to the basic workspace and to other functions that declare these variables global.

 variables in script file : global

MATLAB 입문

44

User-Defined Functions(3/4)

the

order

of arguments is important,

not

the

names

of the arguments

use arrays as input arguments

IML, Chosun

MATLAB 입문

45

User-Defined Functions(4/4)

more than one output

IML, Chosun

MATLAB 입문

46

Variations in the Function Line

Function definition line

File name

1. function [area_square] = square(side);

square.m

2. function area_square = square(side);

square.m

3. function [volume_box] = box(height,width,length);

box.m

4. function [area_circle, circumf] = circle(radius);

circle.m

5. function sqplot(side);

sqplot.m

IML, Chosun

MATLAB 입문

Matlab 기본사용법 47

Methods for Calling Functions

ways to invoke, or “call,” a function into action.

1. As a character string identifying the appropriate function M-file.

function y = fun1(x)

y = x.^2-4;

>>[x, value] = fzero(‘fun1’,[0,3])

2. As an anonymous function(=one-line expression)

>>fun1 = @(x) x.^2-4; >>[x, value] = fzero(fun1, [0,3])

3. As a string expression.

>>fun1 = ‘x.^2-4’; >>[x, value] = fzero(fun1, [0,3]) or as >>[x, value] = fzero(‘x.^2-4’, [0,3])

fhandle=@(argment list) expression

IML, Chosun MATLAB 입문

eval 함수

Matlab 기본사용법 48

문자열을 인수로 사용하여 강력한 문자 매크로 기능을 수행하는 함수

>> x='1/(i+j)';

>> for i=1:3

for j=1:4

A(i,j)=

eval(x)

;

end

end

>> A

A =

0.5000 0.3333 0.2500 0.2000

0.3333 0.2500 0.2000 0.1667

0.2500 0.2000 0.1667 0.1429

>>x=‘1/(i+j)’;

>>for i=1:3,for j=1:4,A(I,j)=eval(x);end,end,A

Main File

x=‘1/(i+j)’;

value=eval_example(x)

Function File

function v=eval_example(x)

for i=1:3,

for j=1:4,

v(i,j)=eval(x);

end

end

(9)

Matlab 기본사용법 49

disp

>>

disp(‘

화면에 출력하고 싶은 내용’

)

>> disp(‘ Programming with MATLAB ')

Programming with MATLAB

>> x=3.56; disp(x)

3.56

>> s=‘1/(i+j)’; disp(s)

1/(i+j)

Matlab 기본사용법 50

Script M-file에서 쓰이는 유용한 함수

명령어

설 명

echo

Displays statements during function execution.

input

Prompts for user input

keyboard

Prompt for user input

pause

or pause(n)

Waits for user response

waitforbuttonpress

stops program execution until a key or mouse

button is pressed over a figure window.

IML, Chosun MATLAB 입문 Matlab 기본사용법 51

Contents 2

• 관계연산자

• 논리연산자

• if ( … else if )

• Switch

• Max, Who, Clear, Break

• Matlab\Toolbox

• Graph 그리기

IML, Chosun MATLAB 입문 Matlab 기본사용법 52

관계 연산자

관계 연산자의 종류(Relational Operator)

<

% 보다 적다.(less than)

<=

% 적거나 같다.(less than or equal to)

>

% 보다 크다.(great than)

>=

% 크거나 같다.(great than or equal to)

==

% 같다.(equal to)

~=

% 같지 않다.(not equal to)

 result=> 1(true) or 0(false)

IML, Chosun MATLAB 입문 Matlab 기본사용법 53

>> 1 == 4

ans = 0

>> 5 < 10

ans = 1

>> A=[1 2;3 4]

>> B=[1 2;2 4]

>> T1= A==B

T1 = 1 1

0 1

>> T2= A~=B

T2 = 0 0

1 0

IML, Chosun MATLAB 입문 Matlab 기본사용법 54

논리연산자

논리 연산자의 종류(Logical Operator)

&

% AND

|

% OR

~

% NOT

A

B

A&B A|B

~A

0

0

0

0

1

1

0

0

1

0

0

1

0

1

1

1

1

1

1

0

연산자 계산

- 우선순위: 산술연산 > ~ > & > |

- 왼쪽에서 오른쪽으로 연산

(10)

Matlab 기본사용법 55

u =[ 1 0 2 3 0 ]

v =[ 5 6 1 0 0 ]

>> u&v

ans = 1 0 1 0 0

>> u|v

ans = 1 1 1 1 0

>> ~u

ans = 0 1 0 0 1

Matlab 기본사용법 56

If

>> a=8

>> if a==8 % 또는

(

a == 8

)

disp('a is eight') ;

b=a/2;

end; b

조건문이 참(

0이 아닌값

) 일 때만 실행문을 수행

If

조건문

실행문 ;

end

IML, Chosun MATLAB 입문 Matlab 기본사용법 57

If … else if

Conditional Statements

 contain one or more of the if, else, and elseif

 The endstatement denotes the end of a conditional statement  The elseand elseifstatements may be omitted if not required.

<example>             0 10 9 0 10 10 9 10 4 15 x if x if x x if x y if x >= 9 y = 15*sqrt(4*x) + 10 elseif x >= 0 y = 10*x + 10 else y = 10 end if expression commands elseif expression commands else commands end

clear all

x=-10:0.01:100;

n=length(x);

for i=1:n

if x(i)>=9

y(i)=15*sqrt(4*x(i))+10;

elseif x(i)>=0

y(i)=10*x(i)+10;

else

y(i)=10;

end

end

plot(x,y)

axis([-10 20 -10 200])

IML, Chosun MATLAB 입문 Matlab 기본사용법 58

실 습

(

if…else if 문 사용)

x 의 값이 1 과 10 사이에 포함된다면 y 에 0을 할당하고

x 의 값이 11 과 20 사이에 포함된다면 y 에 1을 할당하여

y 를 출력하는 문장을 작성하여라.

>> x=5

>> if ( x>=1 & x<=10 )

y=0

else if ( x>=11 & x<=20 )

y=1

end

end

IML, Chosun MATLAB 입문

switch

Matlab 기본사용법 59

변수나 표현에 의해서 실행문을 수행

switch

expression(scalar or string)

case value1

<실행문 1>

case value2

<실행문 2>

·

·

·

otherwise

<실행문 n>

end

IML, Chosun MATLAB 입문 Matlab 기본사용법 60

>> num=0

>> switch num

case -1

disp('negative one');

case 0

disp('zero');

case 1

disp('positive one);

otherwise

disp('other value');

end

>>

ans= zero

(11)

Matlab 기본사용법 61

Useful Commands

>> whos

Name Size Bytes Class A 3x3 72 double array ans 3x1 24 double array

z 1x2 32 double array (complex) Grand total is 14 elements using 128 bytes >> who

Your variables are: ans k t x y z

clc Clears the Command window clf Clears current figure clear Removes all variables from

memory

break Terminates execution of WHILE or FOR loop

exist(‘name’) Determines if a file or variable exists having the name ’name’ quit Stops MATLAB who Lists the variable currently in

memory

whos Lists the current variables and sizes, and indicates if they have imaginary parts

,

Comma; separates elements of

an array

Ellipsis; continues a line

Matlab 기본사용법 62

Clear, Save

&

Load

>> clear

variable

% variables 에 저장된 변수값을 모두 지움

>> save filename

variables

% filename.mat

생성

% variables를 저장(

space

로 구분)

>> load filename

% filename.mat

에서 모든 변수를 읽어 들임

IML, Chosun MATLAB 입문

Toolbox

http://www.mathworks.com/

Matlab 기본사용법 63 IML, Chosun MATLAB 입문 Matlab 기본사용법 64

Sample Model for Simulink

Demo Model for Simulink >> penddemo execution ctrl + click Double-Click IML, Chosun MATLAB 입문

Graph

Plot : 2차원 그림

Plot3: 3차원 그림

Contour: 2차원 등고선 그림

Contour3: 3차원 등고선 그림

Quiver: 벡터량 표시

Grid: 기준선 표시

Matlab 기본사용법 65 IML, Chosun MATLAB 입문 66

Plotting commands

Basic xy plotting commands

Command Description

axis([xmin, xmax ymin ymax]) fplot(‘string’, [xmin xmax])

grid plot(x,y) plot(y) print title(‘text’) xlabel(‘text’) ylabel(‘text’)

Sets the minimum and maximum limits of the x- and y-axes. Performs intelligent plotting of functions, where ‘string’ is a text string that described the function to be plotted and [xmin xmax] specifies the minimum and maximum values of the independent variable. The range of the dependent variable can also be specified. In this case the syntax is fplot(‘string’, [xmin xmax ymin ymax]). Display gridlines at the tick marks corresponding to the tick labels. Generates a plot of the array y versus the array x on rectilinear axes. Plots the values of y versus their indices if y is a vector. Plots the imaginary parts of y versus the real parts if y is a vector having complex values.

Prints the plot in the Figure window. Puts text in a title at the top of a plot. Adds a text label to the x-axis(the abscissa). Adds a text label to the y-axis(the ordinate).

(12)

Plot enhancement commands

Command Description

axes gtext(‘text’)

hold

legend(‘leg1’, ’leg2’, …)

plot (x, y, u, v) plot(x, y, ‘type’) plot(A) plot(P, Q) refresh subplot(m, n, p) text(x, y, ‘text’)

Creates axes objects.

Places the string text in the Figure window at a point specified by the mouse.

Freezes the current plot for subsequent graphics commands. Creates a legend using the strings leg1, leg2, and so on and specifies its placement with the mouse.

Plots, on rectilinear axes, four arrays: y versus x and v versus u. Plots the array y versus the array x on rectilinear axes, using the line type, data marker, and colors specified in the string type.

Plots the columns of the m × n array A versus their indices and generates n curves.

Plots array Q versus array P. See the text for a description of the possible variants involving vectors and/or matrices: plot (x, A), plot (A, x), and plot (A, B).

Redraws the current Figure window.

Splits the Figure window into an array of subwindows with m rows and n columns and directs the subsequent plotting commands to the p-th subwindow.

Places the string text in the Figure window at a point specified by coordinates x, y.

67 68

Plotting with MATLAB

IML, Chosun

MATLAB 입문

69

Subplots

Basic syntax: subplot(m, n, p) <example1>

subplot(3, 2, 5) : This command creates an array of six pane, three panes deep and two panes across, and directs the next plot to appear in the fifth pane (in the bottom-left corner). <example2> x = [0:0.01:5]; y = exp(-1.2*x).*sin(10*x+5); subplot(1,2,1) plot(x,y),xlabel('x'),ylabel('y'),… axis([0 5 -1 1]) x = [-6:0.01:6]; y = abs(x.^3-100); subplot(1,2,2) plot(x,y),xlabel('x'),ylabel('y'),… axis([-6 6 0 350]) IML, Chosun MATLAB 입문 70

The hold Command

holdcommand create a plot that needs two or more plot commands.

be useful with some of the advanced MATRAB toolbox commands that generate specialized plots.

<example>

Annotating Plots

\ tau & \ omega represent the Greek letters τ and ω. ^ : superscript,  _ : subscript. <example> X_{13} x13

>> xlabel('$$\omega\sqrt{x}\sum^n_{i=1} x_{i}$$',‘interpreter','latex','fontsize',24)

>> ylabel('$$\it{Ae}^{-\alpha\it{t}}\sin\beta{\it{t}}$$',‘interpreter','latex','fontsize',24)

-1 0 1 2 3 4 5 6 -1 0 1 2 3 4 5 6 7 y 2 vers us y 1

Im ag(z ) versus Real(z )

IML, Chosun

MATLAB 입문

71

Interactive Plotting in MATLAB

The Plot Tools interface

includes the following three

panels associated with a given

figure.

The Figure Palette: Use this to

create and arrange subplots, to view and plot workspace variables, and to add annotations.

The Plot Browser: Use this to

select and control the visibility of the axes or graphics objects plotted in the figure, and to add data for plotting.  The Property Editor: Use this

to set basic properties of the selected object and to obtain access to all property Inspector.

IML, Chosun

MATLAB 입문

plot

»x=-pi:pi/20:pi;

»plot(x,cos(x),'-r',x,sin(x),'-.b')

»xlabel(

'

\bf{

x axis

}

'

,'fontsize',24)

»ylabel(

'y axis'

)

»title(

'legend function!'

)

»legend('cos', 'sin')

>> print –djpeg example

Matlab 기본사용법 72

Data markers Line types Colors Dot (.) . Asterisk (*) * Cross (x) x Circle (o) o Plus sign (+) + Square (□) s Diamond (◊) d Five-pointed star (★) p Solid line Dashed line -Dash-dotted line -. Dotted line : Black k Blue b Cyan c Green g Magenta m Red r White w Yellow y

Data Markers and Line Types

(13)

plot

»t=[0:10:360]*(pi/180);

»x=2*cos(t);

»y=2*sin(t);

»plot(x,y)

»xlabel('x axis')

»ylabel('\bf{y axis}','fontsize',15)

»title(‘좌표계가 square인 경우!’)

»

axis square

Matlab 기본사용법 73 74

Special Plot Types

Specialized plot commands

Command Description

bar (x, y) loglog (x, y) plotyy(x1, y1, x2, y2) polar (theta, r, ‘type’)

semilogx (x, y)

semilogy(x, y) stairs(x, y) stem(x, y)

Creates a bar chart of y versus x. Produces a log-log plot of y versus x.

Produces a plot with two y-axes, y1 on the left and y2 on the right. Produces a polar plot from the polar coordinates theta and r, using the line type, data marker, and colors specified in the string type. Produces a semilog plot of y versus x with logarithmic abscissa scale.

Produces a semilog plot of x versus y with logarithmic abscissa scale.

Produces a stairs plot of y versus x. Produces a stem plot of y versus x.

IML, Chosun

MATLAB 입문

75

Special Plot Types

Frequency-Response Plots and Filter Circuits

<example> Frequency-Response Plot of a Low-Pass Filter

, where s = ωi and RC = 0.1 second 1 1   RCs A A i o 100 101 102 10-1 100 Frequency (rad/s) Out put /I nput R at io

Frequency Response of a Low-Pass RC Circuit (RC = 0.1 s)

IML, Chosun MATLAB 입문

plot3

»t=0:0.1:10*pi;

»x=exp(-t/20).*cos(t);

»y=exp(-t/20).*sin(t);

»z=t;

»plot3(x,y,z)

»grid on

»xlabel('x')

»ylabel('y')

»zlabel('z')

»title('plot3.m function의 이용법!’)

Matlab 기본사용법 76 IML, Chosun MATLAB 입문 Matlab 기본사용법 77

Manu for Figure Editor

IML, Chosun

MATLAB 입문

contour

»Z=peaks; %matlab

이 제공하는 sample 함수.

»[c,h]=contour(Z);

»set(gcf,'color','w')

»title('contour.m function','fontsize',12)

(14)

contour3

»[X,Y]=meshgrid([-2:0.25:2]);

»Z=X.*exp(-X.^2-Y.^2);

»contour3(X,Y,Z,30)

»hold on

»h=surf(X,Y,Z);

»set(h,'edgecolor',[0.8 0.8 0.8],'facecolor','none')

»hold off

»grid off

»view(-15,25) %방위각:-15, 고도:25

»colormap cool

»set(gcf,'color','w')

»xlabel('x')

»ylabel('y')

»zlabel('z')

»title('contour3.m function')

Matlab 기본사용법 79

quiver

»

x = -3:0.2:3;

»

y = -3:0.2:3;

»

[xx,yy] = meshgrid(x,y);

»

zz = peaks(xx,yy);

»

hold on

»

pcolor(x,y,zz);

»

axis([-3 3 -3 3]);

»

colormap((jet+white)/2);

»

shading interp

»

[px,py] = gradient(zz,0.2,0.2);

»

quiver(x,y,px,py,2,'k');

»

axis off

»

hold off

Matlab 기본사용법 80 IML, Chosun MATLAB 입문 Matlab 기본사용법 81 2D plots IML, Chosun MATLAB 입문 Matlab 기본사용법 82 3D plots

참조

관련 문서

ㆍ 백라이트 교환이 끝나면 , GP에 전원을 투입하고 화면이 올바르게 표시되는지를 확인 하십시오... 긴 수명의 제품을 사용하고 있지만 사용

1. In Control Panel, double-click the System icon. You see the System Properties window.. In System Properties, click the Hardware tab, then click on the Device Manager

평소 흔히 발생할 수 있는 가정집에서 아이들이 뛰어노는 소리, 청소 기나 세탁기를 돌리는 소리, 가구 옮기는 소리 같은 사소하다고 생각 했던 층간소음이

본 논문에 나타낸 3차원 콘볼루션 신경회로망을 이용한 인식 결과를 기존 얼굴 인식방법들인 주성분분석기법(PCA: Principal Component Analysis) 와 2차원

우선 기획단계에는 건설공사에 대한 기본구상을 하고, 건설공사현장을 사전조 사하며 이를 토대로 사업계획을 수립하는 단계이다. 일반적으로 기획단계에서는 발주자가

&lt;그림 9&gt; 경기 악화가 국내 석유화학기업에 영향을

&lt;그림 1&gt;

여자노비로 태어나 어려서 부터 여자의 복식을 하고 바느질을 배우며 자랐으나, 이순지(李純之)의 딸 이씨와 수년 째 간통행각을 벌이다 덜미가 잡힌 인물이었다.. 당시