Matlab Basics Introi
Matlab Basics Introi
Introduction 1. Basic
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 기초
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.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
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
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.
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
you try to command below this line, after refer to the terms of cf/Matrices/About Matrices, entering,
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.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
- 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 기초
>>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)
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
>> x=[1:2:10], length(x) % you remember length() function for calculation the vector length.
x = 1 3 5 7 9 ans = 5
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
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
- 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 기초
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 기초
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) if ... end statement is the basic control of flow. The basic forms are as follows:
if logical_expression
statements
end
Matlab 입문 1 기초
But use the function roots() in Matlab inner function, it is simply obtained.
roots([2 4 -5]) or roots([2 4 5])
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
begin with the English and shall be within 19 characters. It is not distinct
capital or small.
- 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)
global n
t=0; for i=1:n; t=v(i)+t; end
function m=mean(v)
global n
m=sum(v)/n;
- 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 기초
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 기초