What is MATLAB?
- Creator: Cleve Moler, a scientific computing expert
- Primary Purpose: Highly suitable for scientific computing applications/tasks
- General Purpose: Can be used for general-purpose applications, but not as effective
- Alternative Languages**: For non-scientific computing tasks, better to use C++, Java, Python, etc.
Key Features
Performance
- JIT Compilation: From R2015a onwards, uses Just-In-Time (JIT) compilation
- First time a function/script is called → code compiled into machine instructions and stored
- Subsequent calls to same function/script → very fast execution
Built-in Functions
- Optimization: Fully compiled and heavily optimized built-in functions
- Multithreading: Many functions are multithreaded
- Special Instructions: Many exploit special machine instructions for efficiency
- Algorithm Selection: Some choose among different algorithms for most suitable approach
- Numerical Accuracy: All implemented to prevent unnecessary numerical error
- Examples: Functions for solving linear systems, fitting functions to data points, optimizations
Comparison with Other Languages
- Difficulty: Very difficult and time-consuming to implement equivalent scientific computing programs in C/C++, Java, or other general-purpose languages
- Performance: Hard to match MATLAB's speed and accuracy for scientific tasks
Command Window
- Function: Works like command line in Python
- Execution: Statement executed immediately when you press Enter
- Prompt:
>> - Main Usage:
- Call scripts for applications
- Perform simple computations with series of statements
Variables
Basic Usage
- Declaration: Variables can be used without declaration
- Type Selection: MATLAB automatically chooses appropriate types
- Case Sensitivity: Variable names are case-sensitive
- Example:
>> a = 4 % Creates variable a with value 4
>> A = 5 % Different from variable aSpecial Variables
- ans: Stores last output if no variable specified for result
>> 1+1
ans = 2
>> ans+4
ans = 6Text Handling
Character Arrays vs String Arrays
- Character Arrays: Use apostrophes
'text'- Mainly for short pieces of text (shorter overhead) • String Arrays: Use quotation marks
"text" - Come with many functions for working with text as data
- Mainly for short pieces of text (shorter overhead) • String Arrays: Use quotation marks
Examples
>> s = 'This is a character array'
>> st = "This is a string array"Output Control
Suppressing Output
- Method: End statements with semicolon (
;) - Example:
>> s = 'Where is the output?'; % No output displayedFormatting Output
- format compact: Compact display
- format long: Long decimal display
- Example:
>> format compact
>> a = 2.12345 % Shows: 2.1235
>> format long
>> a % Shows: 2.123450000000000Vectors and Matrices
Creation
- Matrix Syntax: Use square brackets
[ ] - Row Separation: Use semicolon
; - Column Separation: Use space or comma
- Examples:
>> A = [1 2; 3 4] % 2x2 matrix
>> b = [-1; 0] % Column vector
>> D = [-3,2,1; 1,0,-2] % 2x3 matrixMatrix Information
- size(): Get matrix dimensions
>> size(D) % Returns [2 3]
>> size(D, 1) % Returns 2 (rows)
>> size(D, 2) % Returns 3 (columns)Transpose
- Operator: Use apostrophe
' - Example:
>> D' % Transposes matrix DRange Creation (Colons)
Basic Syntax
start:end: Creates sequence from start to endstart:step:end: Creates sequence with specified step- Examples:
>> t = 1:6 % [1 2 3 4 5 6]
>> t = 2:2:8 % [2 4 6 8]
>> t = 10:-1:2 % [10 9 8 7 6 5 4 3 2]Matrix Operations
Basic Operations
- Addition/Subtraction: Element-wise with same dimensions
- Multiplication: Standard matrix multiplication rules apply
- Example:
>> A = [1 2; 3 4];
>> B = [-1 -3; -4 0];
>> A + B % Element-wise addition
>> A * C % Matrix multiplication (if dimensions compatible)Matrix Indexing
Key Points
- Starting Index: First index is 1, not 0
- Syntax: Use parentheses
(row, column)
Indexing Examples
>> C = [1 2 3 4 5; 6 7 8 9 10; 11 12 13 14 15];
>> C(2,3) % Returns 8
>> C(1,:) % Returns entire first row
>> C(:,2) % Returns entire second column
>> C(1:2,:) % Returns first two rows
>> C([1 3], [4 2]) % Returns specific elements
>> C(2, 3:end) % From column 3 to end of row 2Assignment
- Modify Elements: Can assign to specific indices
>> C(2,:) = [-1 -2 -3 -4 -5] % Replace entire row
>> C(:,2) = [-9; 0; 3] % Replace entire columnCharacter Array Indexing
ไม่ใช่ String Array นะ if so, we need special method!
- Same Rules: Character arrays follow same indexing rules
>> s = 'Hello, Thailand';
>> s(3:6) % Returns 'llo,'Scripts
Purpose and Usage
- Function: Execute many statements in sequence (like running a normal program)
- File Extension: Save as
.mfiles - Execution: Use filename to run
Example
- File: Save to
ex1.m
a = 4;
b = 2;
c = a+b;
d = c*3 - a- Run: Type
ex1in command window
Text Display
disp() Function
- Purpose: Display text output
- Apostrophe in Text: Use double apostrophes
''to display single apostrophe - Example:
>> disp('What''s up!'); % Displays: What's up!Control Structures
For Loops
- Range Syntax:
for i = 2:6
i
end- Array Syntax:
for j = [3 8 -1 4]
j
endWhile Loops
- Syntax:
i = 2;
while i ~= 5
i = i+1
end~(Tilde) ก็คือ not นั่นแหละ
If Statements
- Full Syntax:
if condition
% code
elseif condition
% code
else
% code
endFunctions
Basic Function Structure
- File Requirement: Filename must match function name • Syntax:
function output = functionName(input)
% function body
endSimple Function Example
- File: Save to
mult2.m
function v = mult2(x)
v = x*2;
endต้องตั้งชื่อ file ให้เหมือนชื่อ function ด้วยนะ แล้วถ้ามีหลาย function ในไฟล์เดียว มันจะ access ได้ function main (ก็น่าจะเป็นชื่อ file) จากนอก file ได้เท่านั้น!!
Multiple Inputs/Outputs
- Syntax:
function [u, v] = foo1(x, y, z)
u = x+y;
v = x*z;
end- Calling:
>> [a, b] = foo1(2, 3, 4) % a=5, b=8Recursion
- Allowed: MATLAB supports recursive functions
- Example: Fibonacci function
function v = fib(n)
if n < 0
error('Invalid input');
elseif n <= 1
v = n;
else
v = fib(n-1) + fib(n-2);
end
endComments and Help
Comments
- Syntax: Use
%for comments
>> x = 2; % This is a commentGetting Help
- Commands:
help functionName- Basic helpdoc functionName- Full documentationhelp *- List all functions
- Examples:
>> help switch
>> doc switch