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

Matlab Basics Introi

The document serves as an introductory guide to MATLAB, covering its basic functionalities, numerical analysis concepts, and matrix operations. It explains the structure of MATLAB, including the Command Window and Editor, and provides details on executing commands, creating M-files, and performing calculations. Additionally, it outlines the importance of numerical analysis methods and their applications in solving mathematical problems.

Uploaded by

MOIZ ALI
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Matlab Basics Introi

The document serves as an introductory guide to MATLAB, covering its basic functionalities, numerical analysis concepts, and matrix operations. It explains the structure of MATLAB, including the Command Window and Editor, and provides details on executing commands, creating M-files, and performing calculations. Additionally, it outlines the importance of numerical analysis methods and their applications in solving mathematical problems.

Uploaded by

MOIZ ALI
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

Matlab 입문 1 기초

Introduction 1. Basic

0.1 What is Numerical Analysis ?

1.1 What Is MATLAB ?


1.1.1 introduction to Matlab
1.1.2 Consist of Matlab

1.2 Basic Direction of Matlab


1.2.1 Start and Folder
1.2.1.1 Start
1.2.1.2 basic calculations
1.2.1.3 Command execute methods
1.2.1.4 CW folder and ME folder
1.2.2 matrixes and Arrays
1.2.2.1 scalar, vector, matrix
1.2.2.2 matrix calculation
1.2.2.3 Procedure of execution statements
1.2.2.4 Others
1.2.2.4.1 Matlab statements and variables
.2.2.4.2 numbers and Arithmetic statements
1
1.2.2.4.3 format for number expression
1.2.2.4.4 information for workspace
1.2.2.4.5 programming tips, help
1.2.2.4.6 quit and saving the work
1.2.3 Operations for matrix and vector
1.2.3.1 transpose matrix
1.2.3.2 size and length of matrix
1.2.3.3 Arithmetic operator
1.2.3.4 operation for matrix and vector
1.2.4 Array operation
1.2.4.1 arithmetic Array operation
1.2.5 Relational operation and Logical operation
1.2.5.1 Relational operation
1.2.5.2 Logical operation
1.3 making M-file and usage
1.3.1 flow control
1.3.1.1 if, else, and elseif
1.3.1.2 switch
1.3.1.3 while
1.3.1.4 for
1.3.1.5 break
1.3.2 make M-file : script and function
1.3.2.1 Script M-files
1.3.2.2 Function M-files
1.3.2.3 global variables
1.3.2.4 string
1.3.2.5 cell matrix
Matlab 입문 1 기초

0.1 What is Numerical Analysis ?

Numeric analysis concerns numeric methods, that is, methods for solving problems in
therms of numbers or corresponding graphical representations by computer or calculator.
The steps from a given situation to the final answer are usually as follow.
(Engineering mathematics 9th ed., Part E chap. 19-21). page 780
1) modeling :
2) Choosing a numeric method
3) programming :
4) Doing the computation :
5) Interpreting the result :
따라서 본 과정이 2학년 초에 개설되어있기 때문에, 1) 미리 주어진 수학적 모형을 수치적
으로 풀기 위하여 2) 어떠한 수치해석 방법을 도입하여야 하는 가를 중점적으로 검토할 것
이다. 아울러 그 때 필요한 3) 서부루틴의 사용방법과 약간의 프로그래밍 기법 등에 대하여
여러 가지 예시를 보여줄 것이다. 또한 4) 계산으로부터 구해진 그림과 print물 등의 해가
5) 물리적의미를 갖는 해가 되는지를 해석하게 될 것이다. 그러므로 이와 같은 수치해법을
이해하고 응용력을 키움으로서 장차 2, 3, 4학년에서 배울 전공에서 수학적 모델링을 세우고
이의 해를 구하는 방법에 대한 이해가 더욱 깊어질 것이며 바로 수치해법을 시도해 볼 수
있을 것이다. 아울러 대학원 과정에서는 얻어진 자료를 해석하기 위하여 다양한 방법들을
사용하는데 그 중 수치해석 기법을 이해하고 있다면 자료해석에 큰 도움이 될 것이다.
The numerical analysis methods in this class are mentioned as below
1) number and error
2) roots of non-linear equations
3) solution of linear simultaneous equations
4) interpolation and curve fitting
5) numerical integration and differentiation
6) solution of ordinary differential equations
7) Optimization
Matlab 입문 1 기초

1.1 What Is MATLAB?

1.1.1 Introduction to Matlab (Matlab help/Contents/MATLAB/Getting Started/Introduction/The MATLAB System)

The name MATLAB stands for MATrix LABoratory which is the program that
consist with numerical analysis, matrix calculation, signal treatment and graphical
representation tools.
Matlab calculation is basically with the matrix and the vector, and its environment.
Matlab has no make dimensioning because of it treat the data as matrix.
There are many functions for numeric calculation in Matlab library. The calculation is
easily made with the functions.
The great merits of Matlab is the use of M-file, you can make the application program
for typical solutions.
1.1.2 Consist of Matlab

Matlab consist with Command window, Editor which make the M-file, Graphical
window which shows the results, and SIMULINK which simulate with various modules.
After the Installation of Matlab, it make the window as follows by automatically.
In the case of it installed, double click the in front window or
Start/Program/MATLAB, it appears as follows. (some differ for the system).

Where,
is the window which show the types of the used variables. In this
time, there no variables because of no data used.
is the window which show the previously used command.
is the Command Window(CW) that make command and show the results.
or is the currently working directory window
which priory refer to the file save, load and execution. Click , change the working
directories. Change the folder to front window as example.
if you click in the right-hand side, separated window is shows.(undock),
in that window or is clicked, return to the original window(dock).
if you click or , the windows disappeared.
if you want to show that, in the templet
, click
.
Matlab 입문 1 기초

1.2 Basic Direction of Matlab

1.2.1 Start and Folder

1.2.1.1 Start
(or >>) in CW was appeared, which the prompt of waiting for the command.
if you putting the command after >>, the results are saved immediately. In this notes,
command statements refer to 굴림체 style. Now type the yellow showed sentence
followed by the >>, click Enter key, verify the Workspace and Command History
windows(basic methods of command input).
(rf 1) is the means of click enter key.
(rf 2) If the mark % is the head of the sentence, it means the explanations of sentences. No typing this is
sure. if you typing the sentences no execution appear. Ignore sentences after %.
>> a=1; b=[1 2];c=[1 2 3; 4 5 6]; % example of scalar, vector, matrix input, details is after...)
>>
There are no change in CW, but you seen the a, b, c in Workspace, in the Command
History windows appear the typed sentences.
This means that the data 1, [1 2] and [1 2 3; 4 5 6] are saved with variables a, b and c,
with no errors. If Error is appeared, that's message is written by red color sentence in
CW.
(rf 3)
If you finding the earlier typed command from the Command History window, then double clicked that, the same commend
executed.
if you right-click the sentence in Command History, it copied. And right-click in the CW, it copy and pasted.
Using the arrows(↑↓→ ←), you can reenter the corrected command sentences the press Enter() key for execution.
If you want to show the saved variables, simply typed variable name and Enter.
>> a 
a =
1
% After from this, omitted the  mark. Although if no , Regard the end of >> to press  key.
% After this, the top of the sentence is >>, it means execute the sentence in CW, if no >> means answer.
% For space saving, answers show with the absence of blank line.
>> b
b = 1 2
>> c
c =
1 2 3
4 5 6
>> a, b % using with comma(,), showing the two more variables.
a = 1
b = 1 2

1.2.1.2 basic calculations


① All arithmetic operation and functions are easily applied as the scientistic calculator.
>> y = cos(pi) % calculate cosine value, pi is  (3.141592).
y = -1
Above sentences, the equal mark(“=”) have two means.
First, (ex, equal sign in >>y = cos(pi)) in the case of using in CW, make the data(numeric or
strings) result from right-hand side execute, and save it to the left-hand side
Matlab 입문 1 기초

variable(y). Then, right-hand side means a data, left-hand side means a variable name.
Second, (ex, equal sign in y = -1) it show the saved results. It means that the saved value
of variable y is -1.
② command sentence is separated with semicolon(;). Then the several command
sentences are made with ; in the same line.
If putting the ; at the end of the command sentence, no echo is made but the calculated
result is saved in memory.
The absence of ; at the end of the command sentence, the calculated result is showed
in CW and saved in memory.
If only arithmetic operation without variable and equal sign, the calculated result is
showed in CW and saved in memory ans.
>> x=1; y=2; x+y % it show the result that saved variable as ans
ans = 3

③ Operating signals
Arithmetic Operators : + - / * ^
Relational Operators : == ~= > < >= <=
Logical Operators : & | ~
Specify evaluation order : ( )
④ There are many saved functions in Matlab . ex) mathematical functions
sin() sine, cos() cosine, tan() tangent, asin() arcsine, sinh() hyperbolic sine
() Natural logarithm, log10() Common (base 10) logarithm, exp() Exponential f., sqrt() Square root, ...
log

⑤ Variable : MATLAB variable names must begin with a letter.


ex) A, a, Aa, a1, a_1, a_12 are different variables. So A and a are not the same variable.
(Matlab help/Search/variable(Programming Tips)

It may be followed by any combination of letters, digits, and underscores(_).


- Although variable names can be of any length, MATLAB uses only the first N characters of
the name, (where N is the number returned by the function namelengthmax), and ignores the rest.
Hence, it is important to make each variable name unique in the first N characters to enable
MATLAB to distinguish variables.
>> N = namelengthmax
N = 63
When naming a variable, make sure you are not using a name that is already used as a
function name. If you define a variable with a function name, you won't be able to call
that function until you either remove the variable from memory with the clear function.
⑥ Verify the exam as a calculator.
Matlab 입문 1 기초

1.2.1.3 Command execute methods


There two methods of the command execution.
① Direct execute in CW as above.
② Make the m-file in which the several calculating procedure were made, and save this
as the file a name of filename.m(this is M-file). If you make the m-file, it is useful for
automating a series of steps you need to perform many times, correction easily, and
re-use after. The term you use for filename becomes the new command that MATLAB
associates with the program. The file extension of .m makes this a MATLAB m-file.
- Making m-file (Very Important)
M-file is made and saved with Matlab Editor(ME).
If you will be make the m-file using the ME, firstly you open the ME.
Using the new M-file icon (or ) in the left-top of Matlab windows, or click the
in for a new m-file open. (if you open the m-file any other methods, No execute)

And then a new m-file opened in the ME as above. Making the program which is a
command series of steps you need to perform, it is similar as in the CW. Typing the
executing commands as below, then the saving and running it by click the ( ) or
press F5.

In this time, if the filename was Untitled*, ME ask you the saving filename.
Below is the example as putting the filename is abc.m. If the file is saved, the icon
is changed as , then the mark * is disappeared in the headline of ME, show the
filename with the saved folder.

The CW showed as below, which is the result of


x+y and sin(pi/2)+tan(pi/4).
Matlab 입문 1 기초

If you want to only saving the file without running, click the icon .
The filename must begin with a letter. although you make the exception of extension
(ex, abc), ME make the m-file with the extension of .m(abc.m) automatically.
In the case of presence of m-file which location is anywhere, you calling the m-file
and modified it to another running. For modifying or saving the m-file, click or press
/Open.
For executing the file in the CW, only type filename. (>>abc )
(There are 3 methods for execute m-file, you know?) ans) press or click F5 or >>filename

1.2.1.4 CW folder and ME folder


CW(Command Window) is the working folder that execute the command now.
ME(Matlab Editor) is the saving folder that save or modify the m-file.
Therefore you know the working procedure because CW or ME folder maybe different.
If you click the  after filename typed in the CW, MATLAB firstly find the filename
in the CW folder. If exist it, MATLAB execute it, if is not exist, MATLAB find it in
the Matlab Path followed by listed folder. Although it is not exist, MATLAB show the
bellow message.
>> abd
??? Undefined function or variable 'abd'.
Therefore if you saved the modified file which is different to CW folder(ex, wallpaper)
you must change the CW folder which place you execute the modified file with click
the in . If you execute the file to a
different location of CW folder, MATLAB ask you to change the folder. If click the yes
key, the Current Directory is changed to the file saved folder.
1.2.2 matrixes and Arrays

1.2.2.1 numeric data : scalar, vector, matrix


cf= Matlab help/Contents/MATLAB/Getting Started/Matrices and Arrays

you try to command below this line, after refer to the terms of cf/Matrices/About Matrices, entering,

subscripts, colon op.

Matlab treat the all numeric data as matrix.


>>clear all; a=3; b=[4 5]; c=[6 7 8; 9 0 1]; % clear all is the command for clearing the all variables.

putting the above command in the work space, 1x1, 1x2, 2x3 matrices is saved.
1x1 matrix is scalar variable.
1x2 matrix is 1column 2row vector variable.
2x3 matrix is 2column 3row matrix variable.
(rf 4) delete the variables in the Workspace, clear variable_name, delete all variables, clear all
clearing the Command Window, clc

1.2.2.2 matrix calculation


1) declare the matrix
Matlab 입문 1 기초

- In MATLAB, a matrix is a rectangular array of numbers


- the data is consist of integer, real, complex, and string
■ there are several methods for saving the matrix to the Matlab workspace as follows
① type directly in Matlab CW. type its elements in [ ].
>>A=[1 2; 3 4];
② declare with inner command statements
>>B=[0:1:10]; % or B=0:1:10; % it means make the 11 elements from 0 to 10 with increment of 1
③ make matrix in M-file
④ reading from the external data file
MATLAB is an interactive system whose basic data element is an array that does not
require dimensioning. This allows you to solve many technical computing problems,
especially those with matrix and vector formulations, in a fraction of the time it would
take to write a program in a scalar noninteractive language such as C or Fortran.
■ rule to make matrix
① Surround the entire list of elements with square brackets, [ ].
② Separate the elements of a row with blanks or commas. (onemore space. if , is placed, ignore space.)
③ Use a semicolon, ; , to indicate the end of each row.
④ Brackets in the open state and wrap the line is mean to another row is started.
ex) A=[1 2; 3 4] or A=[1,2;3,4] or A=[ 1, 2 ; 3 , 4] is the same.
and A=[1 2
3 4] is the same also, it is the example of ④.
2) elements of matrix
- the expression in matlab such as value, variable, equation and string, is used as the
matrix elements. But, values, variables, equations together with strings is not arrowed in
the matrix elements
>> x=[-2.5 sin(2.5) 2*3/4]; % store the results to x for numbers, function values, equation result.
% then column vectors were store to x.
>> x
x = -2.5000 0.5985 1.5000
>> x(2) % if you want to find the second elements in x
ans = 0.5985
>>y=['abc';'x' 'y' 'z'] % store string array to y. store strings between ' ' as string variables
y =
abc
xyz
>>y(2,3) % to find 2nd row and 3rd column of y.
ans = z
if you want to show b? if you want to store abd to variable y1? 답) >>y(1,2) >>y1=y(1,:)

1.2.2.3 Procedure of execution statements


- If you want to execute the statements which have the variables, you should be
declare its value is used before in Matlab workspace, because of the calculation is
sequentially with stored values. if you use the variables which is not declare
preliminary, MATLAB show the Error message.
Matlab 입문 1 기초

>>clear all; clc; x=3.2; y=2.8; z=x+y^2


z =
11.0400
>>clear all; clc; x=3.2; z=x+y^2
??? Reference to a cleared variable y.

1.2.2.4 Others
cf= Matlab help/Contents/MATLAB/Getting Started/Matrices and Arrays
you try to command below this line, after refer to the terms of
cf/Working with Matrices/ all items

cf/More About M and A/all items

cf/Controlling CW In and Output/all items

1.2.2.4.1 Matlab statements and variables


- because of Matlab it the arithmetic language, analysis the equations and calculating
with the equations. Matlab's statements is as follows
>> variable_name = equation
>> equation
The equations are consist of operator, strings, functions and variables, the results are
stored in workspace with matrix its name is variable_name. if no declare for variables,
the results are automatically stored to variable name 'ans' (it means ‘answer’ ).
>> t= 0:1:10 % t is the vector whose elements is consist of form 0 to 10 with increments is 1
>> exp(-t) % show the     exp         ⋯     calculate with above t

>> y= exp(-t); % store the results to y calculate  with above t
% the results is the vector, because of t is the vector.
% This is the great advantage of matlab, which calculate vector calculation

>> y= exp(t); % same above, but instead of 
y = 1.0e+004 * % it means product the value of 1.0e+004(it means 1.0x104 in computer) to answer.
0.0001 0.0003 0.0007 0.0020 0.0055 0.0148 0.0403 0.1097
0.2981 0.8103 2.2026 % 1.0e+004 * 0.0001 is equal to 1.
- If a statement does not fit on one line, use an ellipsis (three periods), ... , followed by
Return or Enter to indicate that the statement continues on the next line. For example,
>> a=2*3 + 4*5 -6*7
a =
-16
>> a=2*3 + 4*5 ...
-6*7
a =
-16

.2.2.4.2 numbers and Arithmetic statements


1

- 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-of-ten scale factor. Imaginary numbers use either i or j as a suffix. Some
examples of legal numbers are
>> -1.23e-2 , 3+j*2
ans = -0.0123 ans = 3.0000 + 2.0000i
Matlab 입문 1 기초

- Expressions use familiar arithmetic operators and precedence rules.


+ addition / right division ' Complex conjugate transpose
- subtraction \ left division ( ) Specify evaluation order
* multiplication ^ Power
/ Slash or matrix right division. B/A is roughly the same as B*inv(A).
\ Backslash or matrix left division. If A is a square matrix, A\B is roughly the same as
inv(A)*B
inf : returns the arithmetic representation for positive infinity. '1/0'
NaN : returns the arithmetic representation for Not-a-Number(NaN), such as '0/0' or 'inf/inf'.
isinf() : Detect infinite elements of an array
isnan() : Detect NaN elements of an array
>> a=1; isinf(a), isnan(a)
ans = 0 , ans = 0 % is not true 0
>> b=1/0
Warning: Divide by zero.
b = Inf
>> isinf(b)
ans = 1 % is true 1

1.2.2.4.3 format for number expression


- By default, numeric output in the Command Window is displayed as 5-digit scaled,
fixed-point values, called the short format. Use the text display preference to change the
numeric format of output for the current and future sessions. The text display format
affects only how numbers are shown, not how MATLAB computes or saves them.
(rf 5) 1.23e-4 is the expression of 1.23x10 in matlab.
-4

>> format long ; -5/4, 1.23456e-6, 12345.6


ans = -1.25000000000000 ans = 1.234560000000000e-006 ans = 1.234560000000000e+004
>> format short ; -5/4, 1.23456e-5, 12345.6
ans = -1.2500 ans = 1.2346e-006 ans = 1.2346e+004 % significant figure 5 with round off.
>> format rat ; -5/4, 1.23456e-5, 12345.6
ans = -5/4 ans = 1/810005 ans = 61728/5
format -5/4 1.23456e-5 12345.6
short -1.2500 1 sign 5 mantissa 1.2346e-005 1.2346e+004
short e -1.2500e+000 4 exponent 1.2346e-005 1.2346e+004
long -1.25000000000000 15 mantissa 1.234560000000000e-005 1.234560000000000e+004
long e -1.250000000000000e+000 1.234560000000000e-005 1.234560000000000e+004
bank -1.25 point below 2 0.00 12345.60
hex bff4000000000000 16 digit 3ee9e3fe580f5495 40c81cccccccccd
+ - negative or positive + +
rat -5/4 rational 1/810005 61728/5
(rf 6) 1.25e+000 is the format for 'short e'; Change format to short for latter use, immediately.
1.2.2.4.4 information for workspace
the used variables are stored in the 'workspace'. if you show the used variables, type
who or whos.
who lists the variables currently in the workspace.
whos lists the current variables and their sizes and types. It also reports the totals for sizes.
Matlab 입문 1 기초

>>who
Your variables are:
A i y z1
ans x z
>>whos
Name Size Bytes Class
A 4× 3 96 double array
ans 1× 1 8 double array
I 1× 1 8 double array
x 1× 5 40 double array
y 2× 3 12 char array
z 1× 1 16 double array(complex)
z1 1× 1 16 double array(complex)

Grand total is 27 elements using 196 bytes

1.2.2.3.5 programming tips help


- MATLAB provides extensive documentation, in both printed and online format, to help
you learn about and use all of its features. If you are a new user, start with this
Getting Started book. It covers all the primary MATLAB features at a high level,
including many examples. The MATLAB online help provides task-oriented and
reference information about MATLAB features. MATLAB documentation is also
available in printed form and in PDF format. type now
>> help clc %or help home %or help format %or help isinf %or help inf etc,...
lookfor : Search for specified keyword in all help entries.
lookfor topic searches for the string topic in the first comment line (the H1 line) of
the help text in all M-files found on the MATLAB search path. For all files in which a
match occurs, lookfor displays the H1 line. try now,
>> lookfor inv
When press Ctrl and c, terminate the searches.
1.2.2.3.6 quit and saving the work
- To quit MATLAB at any time, do one of the following:
Click the close box in the MATLAB desktop.
Select Exit MATLAB from the desktop File menu.
Type quit at the Command Window prompt.
Unless unsaved files are open, MATLAB closes immediately. Therefore you should save
the m-files, if you want to recall the m-files.
1.2.3 Operations for matrix and vector

1.2.3.1 transpose matrix


- For real matrices, the transpose operation interchanges  and  . MATLAB uses the
 

apostrophe (or single quote ') to denote transpose.


>>clear all; A=[1 2 3; 4 5 6; 7 8 9; 10 11 12]
A =
1 2 3
Matlab 입문 1 기초

4 5 6
7 8 9
10 11 12
>>A'
ans =
1 4 7 10 % interchange column and row.
2 5 8 11
3 6 9 12

1.2.3.2 size and length of matrix


[m,n] = size(X) returns the size of matrix X in separate variables m and n
n = length(X) returns the size of the longest dimension of X. If X is a vector, this is
the same as its length.
>> size(A) % help size
ans = 4 3 % 4 column 3 row matrix
>>[m n]=size(A) % if you want to save the number of column and row
m = 4
n = 3
>> length(A) % help length
ans = 4 % show the larger value of column or row

>> x=[1:2:10], length(x) % you remember length() function for calculation the vector length.
x = 1 3 5 7 9 ans = 5

1.2.3.2 Arithmetic operator


1) Addition and Subtraction
>>A=[1 2 3;4 5 6];
>>B=[2 4 6;1 3 5];
>>C=A+B
C =
3 6 9
5 8 11
>>C-5
ans =
-2 1 4
0 3 5
2) Matrix multiplication
>> A*B
??? Error using ==> *
Inner matrix dimensions must agree.
>>A*B'
ans =
 
28
64
22
49
%
 
  ×    ·  ·  · ·  ·  ·  
   ·  ·  · ·  ·  ·  
 

3) Slash or matrix right division, Backslash or matrix left division


▷ Backslash : X=A\B ---> solution of A*X=B (X = inv(A)*B)
▷ Slash : X=A/B ---> solution of X*B=A (X = A*inv(B))
>>clear all;
>>A=[1 2;3 4];
>>B=[5 6;7 8];
>>X=A\B
Matlab 입문 1 기초

X =
-3 -4
4 5
>> X1=A/B
X1 =
3.0000 -2.0000
2.0000 -1.0000
>> inv(A)*B >> A*inv(B)
ans = ans =
-3.0000 -4.0000 3.0000 -2.0000
4.0000 5.0000 2.0000 -1.0000

1.2.3.3 operation for matrix and vector


1) make the vector
- start_v : increment_v : end_v is make the vector. if not declare increment_v, make
the vector whose increment is one.
>>x=1:5
x = 1 2 3 4 5
>>y=0:.5:3 % increment is 0.5
y = 0 0.5000 1.0000 1.5000 2.0000 2.50000 3.0000
>>z=5:-1:-5
z = 5 4 3 2 1 0 -1 -2 -3 -4 -5
>> length(z) >> size(z) % what is the function size() and length()? 답) 11쪽 참조
ans = 11 ans = 1 11
make the vector using the colon(:), it make the row vectors, if you want to make
column vectors, use small quotation mark(').
>> zz=z'
>> length(zz) >> size(zz)
ans = 11 ans = 11 1

- other vector making functions


▷ linspace() : % help linspace
>> linspace(1, 3, 6) % generates linearly equally spaced 6 points between 1 and 3.
ans = 1.0000 1.4000 1.8000 2.2000 2.6000 3.0000
>> x=linspace(1, 3); % generate linearly equally spaced 100 points, for absence of third term.
>> size(x)
ans = 1 100
▷ logspace() : % generate logarithmically equally spaced points . help logspace
>> logspace(0,3,4) % generate 4 logarithmically equally spaced points between decades from 100 to 103.
ans = 1 10 100 1000
>> y=logspace(0,3); size(y)
ans = 1 50 % generate 50 logarithmically equally spaced, for absence of third term.

2) index
- To access a single element of a multidimensional array, use integer subscripts. Each
subscript indexes a dimension--the first indexes the row dimension, the second indexes
the column dimension. ex) A(1,2) is access 1st row 2nd column of A.
if you want to put the index with equation rather than integer value, the result of
equation is must to be integer.
Matlab 입문 1 기초

>>clear all; A= [ 0 1 2; 4 5 6; 8 9 10 ]
A =
0 1 2
4 5 6
8 9 10
>>A(1,1) = A(2,2)-A(3,3) % values of row 2 column 2 - row 3 column 3, put it to row 1 column 1 of A.
A =
-5 1 2
4 5 6
8 9 10
▶ Select a subset of elements (submatrix) from a matrix with specified index.
- method : (start_row : end_row , start_column : end_column)
>>clear all; A=[ 11 12 13 14 15; 21 22 23 24 25; 31 32 33 34 35; 41 42 43 44 45]
A =
11 12 13 14 15
21 22 23 24 25
31 32 33 34 35
41 42 43 44 45
>>size(A)
ans = 4 5 % A have 4 rows 5 columns.
>> A(1:4, 3) % row of 1 to 4, column 3 elements of A (it makes column vector)
>> A(1:3, 2:3) % row of 1 to 3, column of 2 to 3 elements (submatrix 3× 2)
>> A(1:2, :) % row of 1 to 2, all column elements (submatrix 2× 5)
>> A(:, 5) % all row, column 5 elements (4× 1 column vector). : means all elements row or column.
% if you want to show the 3rd row and all column of A? 답) >>A(3,:)

3) Empty matrix
A matrix having at least one dimension equal to zero is called an empty matrix. The
simplest empty matrix is 0-by-0 in size. Examples of more complex matrices are those
of dimension 0-by-5 or 10-by-0
>>x=[ ]
x =
[ ]
- You can delete rows and columns from a matrix using just a pair of square brackets.
>>A=[1 2 3; 4 5 6; 7 8 9]
A =
1 2 3
4 5 6
7 8 9
>>A([1 3], : )= [ ] % replace 1st row and 3rd row and all columns with null
A =
4 5 6
- to clear 2nd element of A? result is? 답) >>A(2)=[] A= 4 6

- what means of A(:)=[] ? 답) >>A(:)=[] A= []

- You can clear a variable A, which removes it from the workspace. clear A
- you can clear all variable, which removes it from the workspace. clear all
4) general basic matrices
MATLAB provides 3 functions that generate basic matrices.
▷ zeros() - all zeros
Matlab 입문 1 기초

▷ ones() - all ones


▷ eye() - Identity matrix
with one index(n), matlab makes square matrix of nxn.
with number of row n and number of column m, matlab makes matrix of nxm.
verify next
zeros(3) zeros(2,3) zeros(3,1)
ones(3) ones(1,3) ones(3,2)
eye(3) eye(1,3) eye(3,2)
make next matrix only use with above.
A =
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 1 0 0
0 0 0 0 1 0
0 0 0 0 0 1

1.2.4 Array operation .* ./ .^


- When they are taken away from the world of linear algebra, matrices become
two-dimensional numeric arrays. Arithmetic operations on arrays are done element by
element. This means that addition and subtraction are the same for arrays and matrices,
but that multiplicative operations are different. MATLAB uses a dot, or decimal point,
as part of the notation for multiplicative Array operations.
1.2.4.1 arithmetic and Array operation
1) addition and subtraction
- addition and subtraction are the same for arrays and matrices.
2) multiplication
- but that multiplicative operations are different. the operator is .* ,
making new matrix with multiplicative of elements to elements for same positions, if the
size of two matrix is differ, Error message is appeared.
>>A=[1 2 3;4 5 6];
>>B=[1 3 6;7 8 9];
>>A .* B
ans =
1 6 18 % 1x1 2x3 3x6
28 40 54 % 4x7 5x8 6x9

3) division
- and that division operations are different. the operator is ./ and .\ (or .\)
making new matrix with division of elements to elements for same positions, if the size
of two matrix is differ, Error message is appeared.
>>A ./ B % elements of A divide by elements of B.
ans =
1.0000 0.6667 0.5000 % 1/1 2/3 3/6
0.5714 0.6250 0.6667 % 4/7 5/8 6/9
Matlab 입문 1 기초

>>A .\ B % elements of B divide by elements of A.


ans =
1.0000 1.5000 2.0000 % 1/1 3/2 6/3
1.7500 1.6000 1.5000 % 7/4 8/5 9/6
>>B ./ A % it same to A.\B
ans =
1.0000 1.5000 2.0000
1.7500 1.6000 1.5000
ex) When Celsius Temperature C is the vector from 0 to 100 with increment of 10.
convert to the Temperature of Fahrenheit F, Absolute T and 1000/T(=aT).
>>C=[0:10:100];
F=C*1.8 + 32
F =
32 50 68 86 104 122 140 158 176 194 212
>>T=C+273.15
T =
273.1500 283.1500 293.1500 303.1500 313.1500 323.1500 333.1500 343.1500
353.1500 363.1500 373.1500
>>aT=1000 ./T % use array operation
aT =
3.6610 3.5317 3.4112 3.2987 3.1934 3.0945 3.0017 2.9142
2.8317 2.7537 2.6799
or
>>aT= 1000 ./(C+273.15) % one cue

3) Element-by-element power
- the operator is .^
>>x=[1 2 3];
>>y=[4 5 6];
>>y .^ 2
ans =
16 25 36 % square of each elements

>>x .^ y
ans = 1 32 729 % 1^4 2^5 3^6

1.2.5 Relational operation and Logical operation

1.2.5.1 Relational operation


The relational operators are <, >, <=, >=, ==, and ~=.
Relational operators perform element-by-element comparisons between two arrays.
They return a logical array of the same size, with elements set to true (1) where the
relation is true, and elements set to false (0) where it is not.
operator means
< less than
<= less than and equal
> greater than
>= greater than and equal
== equal
~= not equal
>>clear all; a=[2 3 ; 4 5]; b=[0 3; 3 7];
>> d = a>b
d = 1 0 % 2>0 is true 1, 3>3 is false 0
Matlab 입문 1 기초

1 0 % 4>3 is true 1, 5>7 is false 0

1.2.5.2 logical operation


The symbols &, |, and ~ are the logical array operators AND, OR, and NOT.
They work element by element on arrays, with 0 representing logical false, and
anything nonzero representing logical true. The logical operators return a logical array
with elements set to true (1) or false (0), as appropriate.
major usage of these operator is in if, switch, and while statements.
operator means
& and
| or
~ not
▷ C = A & B % return 1 for both element is not 0, 0 for other cases.
>>A=1; B=0; C = A & B
C = 0 % 1&0 is 0
>>c = a & b
c = 0 1 % 2&0 is 0 3&3 is 1
1 1 % 4&3 is 1 5&7 is 1
▷ C = A | B % return 0 for both element is 0, 1 for other cases.
>>A=1; B=0; C = A | B
C = 1 % 1|0 is 1
>> c = a | b
c = 1 1 % 2|0 is 1 3|3 is 1
1 1 % 4|3 is 1 5|7 is 1
▷ B = ~A % return 0 for the element is 1, 1 for other case.
>>A=1; B = ~A
B = 0
>> C = ~a
C =
0 0
0 0
>> C = ~b
C =
1 0
0 0

1.3 making M-file and usage

1.3.1 flow control

cf= Matlab help/Contents/MATLAB/Getting Started/programming/flow control


/Scripts and functions
MATLAB has several flow control constructs
if, switch and case, for, while, continue, break, try - catch, return

3.1.1 if, else, and elseif statements


1. (Matlab help/Contents/MATLAB/Programming/Flow Control/if )

1) if ... end statement is the basic control of flow. The basic forms are as follows:
if logical_expression
statements
end
Matlab 입문 1 기초

where logical_expression is the condition of if statement. the condition is the result of


relational operator (or logical operation for relational operator), which is true(1) or
false(0). If the condition is true, execute next statements (available several sentences),
but false not execute anything.
ex) open m-file and type below then save it with abc.
%abc.m
if aa==3 % logical_expression
bb=0.2; % statements
end
aa, bb % this line shows aa and bb
>>clear all; abc
??? Undefined function or variable 'aa'.
because of absence , error message appeared.
aa
now in CW
>>aa=3; % enter variable aa
>>abc % this is the method of executing for saved m-file.
>>aa=3; abc % same as above. >> enter variable aa; file name 
>>aa=2; abc % the result is true?
>>clear all; aa=2; abc % what is differ above?

next is same, but a statement does fit on one line.


>> if a==3, b=0.2; end; a, b
using the comma(,) or output suppression(;), fit the several commands on one line.
next example is use to both relational and logical operator in logical_expression.
if a==3 | a==5; b=0.2; end % a is 3 or 5, save 0.2 to b.
if (a==3 | a==5); b=0.2; end %

2) if ... else ... end statements.


if logical_expression
statements 1
else
statements 2
end
logical_expression is true, statements 1 execute, otherwise statements 2.
ex) find the roots of quadratic equation ax^2 + bx + c = 0,
make m-file(aaa.m) using an if statement.
D= b^2-4*a*c;
if (D >=0), x1= (-b+sqrt(D) )/(2*a); x2= (-b-sqrt(D) )/(2*a); % sqrt is square root
else x1= (-b+sqrt(-D)*i )/(2*a); x2= (-b-sqrt(-D)*i )/(2*a);
end
x1,x2

execute aaa? save above to aaa.m, >> enter a,b,c; filename;

>>a=2;b=4;c=-5; aaa % real roots -2.8708 and 0.8708


>>a=2;b=4;c=5; aaa % complex roots -1.0000 + 1.2247i and -1.0000 - 1.2247i

But use the function roots() in Matlab inner function, it is simply obtained.
roots([2 4 -5]) or roots([2 4 5])
Matlab 입문 1 기초

3) elseif statements. this is similar switch statements.


if logical_expression 1
statements 1 logical_expression is needed just after if and elseif
elseif logical_expression 2 logical_expression is not need after else.
statements 2 end is just need after the end of if statements
logical_expression is true, next statements execute
elseif logical_expression 3
statements 3 logical_expression is not true anyone, else statements below is execute
else
statements 4
end

make m-file and execute


if n < 0
fprintf('Negative\n');
elseif n == 0
fprintf('Zero\n');
else
fprintf('Positive\n');
end
the function fprintf(' ') is the command which print out the CW between quotation mark ' '.
\n in ' ' is the command of line change. Described in detail later.
this is the example, printout depending on the value of n is -, 0, or +.

1.3.1.2 switch statement


The switch statement is very similar, if you use multiple if elseif statements.
The basic forms are as follows:
switch expression
case value1
statements 1
case value2
statements 2
.
.
otherwise
statements n
end
Each value corresponds to the value of expression as it is running just below the
statements. Otherwise, execute otherwise following statements. It is more cleanly then
using if-elseif-end statements.
ex) make m-file and execute, no variable are required.
%abc.m
switch i
case 3 ; fprintf('three\n');
case 4 ; fprintf('four\n');
otherwise; fprintf('^-^\n');
end

>> i=1; abc %^-^


>> i=2; abc %^-^
>> i=3; abc %three
>> i=4; abc %four
>> i=5; abc %^-^
Matlab 입문 1 기초

1.3.1.3 while statement


The while loop repeats a group of statements an indefinite number of times under
control of a logical condition. A matching end delineates the statements.
while expression
statements
end
the statements is execute, during the expression condition is true(1), and exit to while
statement when condition is false(0).
Here is a complete program, illustrating while, if, else, and end, that uses interval
bisection to find a zero of a polynomial.
a = 0; fa = -Inf;
b = 3; fb = Inf;
while b-a > eps*b
x = (a+b)/2;
fx = x^3-2*x-5;
if sign(fx) == sign(fa)
a = x; fa = fx;
else
b = x; fb = fx;
end
end
x

The result is a root of the polynomial x3 - 2x - 5, namely


x = 2.09455148154233

1.3.1.4 for statement (very important)


In fact, while statements discussed above, more than a for statement is used. Because
of for statement is more repeatable flow control.
for index = start_v : increment_v : end_v
statements
end
It is need to index of for statement, index is need to start_v : increment_v : end_v.
make the m-file to sum from 1 to 10, execute, no variable are required..
% sample.m
sum=0;
for n=1:10 % it is same to for n=1:1:10. may skip the increment is 1.
sum=sum+n;
fprintf('%d %d \n', n, sum);
end
result
1 1
2 3
skip
10 55
It is more repeatable flow control rather than while statement.
When running the following examples, does not show x but saved. show x, type x.
>>clear all;
for i = 1 :10;
x(i) = i;
end
>> x
Matlab 입문 1 기초

x= 1 2 3 4 5 6 7 8 9 10
try again absence of ; and existence of ; in line 3 x(i) = I;
1.3.1.5 break statement
The break statement lets you exit early from a for loop or while loop. In nested loops,
break exits from the innermost loop only.
In above example of sum of square from 1 to 10, exit for statement if i is 7.
for i=1:10
j=i^2;
if i==7; j, I, break; end
end
>>clear all; i=1 ;
while i<=10
j =i^2; i=i+1;
if i==7; j, i, break; end;
end

1.3.2 Make M-file : script and function (Very Important)


cf= Matlab help/Contents/MATLAB/Getting Started/programming/Scripts and functions
- A series of Matlab commands is saved in m-file, it can be run at once.
It is called to ‘m-file’, including the series of Matlab commands, because of it's
extension is ‘m’. This extension ‘m’ means macro file.
This m-file made with Matlab Editor(ME), it consist of ASCⅡcode. (if you have not
written with ME, it is not executable). When you save the m-file, the name must

begin with the English and shall be within 19 characters. It is not distinct

capital or small.

- scripts and function


▷ Scripts file : Scripts are simply files containing a sequence of MATLAB statements.
(it is often called main file).
▷ function file : it is similar to script file, but Functions make use of their own local
variables and accept input arguments. It starts with function at the top of line.
1.3.2.1 Scripts file
- When you invoke a script, MATLAB simply executes the commands found in the file.
Scripts can operate on existing data in the workspace, or they can create new data on
which to operate. Although scripts do not return output arguments, any variables that
they create remain in the workspace, to be used in subsequent computations. In addition,
scripts can produce graphical output using functions like plot.
3.2.2 function file
1.

- Functions are M-files that can accept input arguments and return output arguments.
The names of the M-file and of the function should be the same. Functions operate on
variables within their own workspace, separate from the workspace you access at the
MATLAB command prompt.
Matlab 입문 1 기초

The head of first line of m-file start with function, it means that file is function file.
This is major difference between script and function file. if absence of function is
script file.
function passing_values = function_name(passed_variables)
-When you need to save the file name must be the same as the function_name.
- passed_variables can be passed from a script file or other functions to the function,
and the function can be passed passing_values to its calling file. The passing_values are
listed in order.
- the function does not execute itself, it should be calling in a script file or other
function file. (Execute function file directly, error message is appeared.)
ex) Type the following in ME, and save test1.m.
function [tot, avg]=test1(A)
% TEST1 find mean and total value with vector
n=length(A);
tot=0;
for i=1:n ;
tot=A(i)+tot;
end
avg=sum(A)/n;
Execution is
>> A=[1 2 3 4 5]; [t1, a1]=test1(A)
t1 = 15
a1 = 3
explain) values passing order, 1) green, 2) red, 3) purple.
1) store A and calling the function test1 with passed_variables A in CW.
2) calculate passing_value tot and avg in the function test1. and pass these values to call function.
3) the results is stored to t1 and a1 with listed order.
*) if the passing_value is not calculated in the function test1, error message is appeared.
▶ Subfunctions
- function file may have one or more functions in itself, the named file is the primary
function and inner function is the subfunctions.
- individual subfunctions are similar to primary function, but its name is need to differ.
- subfunction can not call anywhere else(ex, script), it can call only in the function file.
Type the following in ME, and save test2.m.
function [tot, avg]=test2(A) % TEST2 find mean and total value, it has two sub functions.
n=length(A); tot=total(A,n); avg=mean(A,n);

function t=total(v,n) % Calculate total value. subfunction 1


t=0; for i=1:n; t=v(i)+t; end

function m=mean(v,n) % Calculate average. subfunction 2


m=sum(v)/n;
>> A=[1 2 3 4 5]; [tot, avg]=test2(A)
tot = 15
avg = 3
the procedure is increase, but process is same. tot=total(A,n) is pass A and n to
function total, calculate tot in total and pass to it. The values is pass with the lister
order, not value name.
Matlab 입문 1 기초

1. 3.2.3 global variable


- If you want more than one function to share a single copy of a variable, simply
declare the variable as global in all the functions. Do the same thing at the command
line if you want the base workspace to access the variable. The global declaration must
occur before the variable is actually used in a function.
In the case of several variables to be declare global, variable names should be listed
separated by space.
Type the following in ME, and save test3.m.
function [tot, avg]=test3(A)
global n
n=length(A); tot=total(A); avg=mean(A); % because the n to global, n must delete.

function t=total(v)
global n
t=0; for i=1:n; t=v(i)+t; end

function m=mean(v)
global n
m=sum(v)/n;

>>clear all; A=[1 2 3 4 5]; [tot, avg]=test3(A)


the next is same, but with global declaration.
function tot=test4f
global n A avg
n=length(A); tot=sum(A); avg=tot/n;

>> clear all; global n A avg; A=[1 2 3 4 5]; t=test4f;


n, t, avg

1.3.2.4 String cf= Matlab help/Contents/MATLAB/Getting Started/programming/other Data structure


S = 'Any Characters' creates a character array, or string. The string is actually a vector
whose components are the numeric codes for the characters (the first 127 codes are
ASCII). The actual characters displayed depend on the character set encoding for a
given font. The length of S is the number of characters. A quotation within the string
is indicated by two quotes. String variables can not be used in the calculations, but it
used in plot of figure or string treatment functions such as findstr(), strcmp(),etc.
>>s='Matlab'
s = Matlab
>>size(s)
ans = 1 6 % its elements are 6.

- if you want to make another string in the string, it is similar to indexing of vector.
>>b=s(4:6) % from 4 to 6 of s
b = lab

- if you want to make long string with small strings, bracket [ ] is used.
>>[s ' function''s Test']
ans =Matlab function's Test % Create a simple string that includes a single quote.

- The num2str() function converts numbers to their string representations. This function
Matlab 입문 1 기초

is useful for labeling and titling plots with numeric values.


- str = int2str(N) converts an integer to a string with integer format. The input N
can be a single integer or a vector or matrix of integers. Noninteger inputs are rounded
before conversion.
str = num2str(A) converts array A into a string representation str with roughly four
digits of precision and an exponent if required.
str = num2str(A, precision) converts the array A into a string representation str with
maximum precision specified by precision. Argument precision specifies the number of
digits the output string is to contain. The default is four.
x = str2num('str') converts the string str, which is an ASCII character representation
of a numeric value, to numeric representation.
>>a=12.345678; T1=273; T2=373;
>>as= num2str(a,4); T1s=int2str(T1); T2s=int2str(T2);
>>eq=['Activation E.=', as, ' kcal/mol for ', T1s, '-', T2s, 'K']
eq= Activation E.=12.35 kcal/mol for 273-373K
>>aaa=str2num(as)
aaa = 12.3500

1.3.2.5 cell Array


there are string array and cell array .
>> A=['a11' 'a12' ; 'a21', 'a22'] % string matrix make with [ ]. length must be same.
A=
a11a12 % it appears without ' ' in CW
a21a22
>>size(A) -> ans= 2 6 % 2 row 6 column string array
>> A={'a11' 'a12' ; 'a21', 'a222'} % cell array make with { }, is irrespective of the length.
A =
'a11' 'a12' % it appear with ' ' in CW.
'a21' 'a222'
>>size(A) -> ans= 2 2 % 2 row 2 column cell array

- rule to make cell matrix


▷ They enclose the entire string in { } brackets.
▷ for columns differ, strings are separate with comma or blank.
▷ for rows differ, strings are separate with semicolon( ; )
>> A={'a11' 'a12' ; 'a21', 'a222'}
A = 'a11' 'a12'
'a21' 'a222'

cell matrix by using a vector index, the portion of the matrix can be assigned to a
variable sub cell, such as when dealing with a numerical matrix () is used.
>>A12=A(1,2) ans) A12 = 'a12'
convert cell variables to string variables, use cell variable{ }.
>>b11=A{1,1} ans) b11 =a11
>>b11(1) ans) ans =b
>>b12=A{1,1}(1:2) ans) b12 =a1
Matlab 입문 1 기초

Matlab introduction 1 Basic. Summary


1) rule of make m-file, save, execute, file name
2) variables of scalar, vector, matrix
rule of variable naming -> must begin with a letter, differ to capital and small
make matrix -> comma, space, semicolon ; , colon : , parenthesis ()
saving variable -> use equal mark =
show variable -> variable name enter, without semicolon enter
usage ->
3) make equation and show it
4) 2 means of equal mark =
5) mathematical function of scientific calculation
6) operators : Arithmetic, Array, relational, logical, evaluation order
7) function length() and size()
8) make vector variable with increment
9) zeros(), ones(), eye()
10) what is array operation ?
11) if statements
12) for statements
13) function m-file?
14) make string -> ' '
15) usage of [ ] to make string
16) function num2str() -> convert number to string
17) cell variables

You might also like