matlab-intro
basics: number
binary systems, difference between MB and Mb, GB, TB, ASCII, unicode… (stupid definitions)
how to represent the signed format?
8 bits: 1 for sign and 7 for numbers
Two’s complement: invert all the bits of a, add 1 to get −a
e.g. :
00101010 → 11010101 + 1 = 11010110
00101010 = 0 · 2 7 + 2 5 + 2 3 + 2 = 42
11010110 = −1 · 2 7 + 2 6 + 2 4 + 2 2 + 2 = 86 − 128 = −42
Data Type for Matlab
In this section, we will learn some basic data types in computer and their conversion in MATLAB.
1. Numeric Types
There are two basic types of data, numeric and characters/strings.
| type name | definition |
|---|---|
| double | Double-precision arrays |
| single | Single-precision arrays |
| int8 | 8-bit signed integer arrays |
| int16 | 16-bit signed integer arrays |
| int32 | 32-bit signed integer arrays |
| int64 | 64-bit signed integer arrays |
| uint8 | 8-bit unsigned integer arrays |
| … | … |
2. Simple Conversion
Conversion between numeric:
1 | num1=int32([-20,20]); % a (1, 2) array |
3. String/Character Types
| type name | definition |
|---|---|
| string | string arrays |
| char | Character arrays |
| strings | String arrays with no characters |
Compare the following two cases:
1 | c='Welcome to VG101'; % char |
calculation
numeric calculator
Addition: +
Subtraction: -
Multiplication: *
Power:^
Right division: /
Left division:
π: pi
sqrt(-1): i or j
infinity: Inf
other operators
char operator: ischar
String calculator: +
basic matlab grammar
input&output
1 | clearvars, clc; %clear all of the varibles and the command lines |
arrays
initialzation
Array initialization: manualorviafunction
1 | array_example_1D=[1,2,3] |
Colon operator: initial : step: end
1 | colon_example_nostepsize=[1:5] |
operation
basic arithmetic: addition M + 2, subtraction, multiplication
Impose other function sin(M)
array operation
- element-wise: Add a “.” in front of each operation, e.g. .* , like A .* B
- matrice-wise:
- Conjugate transpose: ’
- Inverse: inv
- reshape:
reshape(A, newsize)reshape the size of A tonewsize - sum:
sum(A)sum up all the elements in A det(A): calculate the determinanteig(A): calculate the eigenvalue and eigenvector
matrix
1 | A = [1,2,3,4,5,6,5,4,6] |
Given a matrix, elements can be accessed by:
- Coordinates: use the (row,column) position
A(1, 2) - Indices:
- Use a single number representing a position
A(2) - The top left element has index 1 (column-first indexing)
- The bottom right: “number of elements”
- Use a single number representing a position
- partial indexing: colon operator
Advanced data type: cell array
Acell array is a composite data type that groups related data using data containers called cells. Each cell can contain any type of data.
1 | a{1,1} =[13−7;206;051]; |
logic operator
normal operator
| Operator | Description |
|---|---|
| && | Short circuit logical AND |
| || | Short circuit logical OR |
| & | Bitwise logical AND |
| | | Bitwise logical OR |
| example: |
1 | x = (1 > 2) && (3 > 2) |
order of precedence:
![[Pasted image 20240530100251.png]]
if statement
1 | if <expression> |
example:
1 | a = 10; |
if-else statement
1 | if expression1 |
switch-case-end statement
1 | switch <num/strings> |
exception handling machanism
1 | try |
for loop
1 | for i = <initial value> : <step length>: <end value> |
while loop
1 | while <boolean expression> |
example:
1 | while 1 |
break and continue: the same as C++
vectorization
the process of revising loop-based, scalar-oriented code to use MATLAB matrix and vector operations.
example:
1 | i=0; |
vectorization:
1 | t=0:0.01:10; |
In Matlab, order of preference: vectorization, for, and while
function
sub-function
- A main function has the same name as the filename
- A main function is the only function that can be called outside
- Sub-functions: only accessible by functions from the same file
- Sub-functions are often used to implement ‘utility‘ calculations for a main function
definition
1 | function [out_arg1, out_arg2] = function_name(in_arg1, in_arg2) |
pass-by-value scheme
MATLAB makes a copy of the actual parameter and passes them to the function.
other common functions
file SL
basic ones
- save varibles:
save(’filename’,’var1’,’var2’,...,’format’) into filename.mat - load varibles:
load('file', 'format')
high-level file IO
supporting format:
- matlab formatted data .mat
- text .csv, .txt, etc.
- spreadsheet .xls, etc.
- image .bmp, .png, etc.
- audio, video, etc.
A=importdata(filename)
random number generation
- A nxm matrix of random numbers:
rand(n,m) - A nxn matrix of random integers between
mandM:randi([m M],n) - A random permutation of the integers 1:N:
randperm(n) - Random number generator: Syntax:
rng(seed,generator);- Random numbers are generated by deterministic algorithm
- Seed controls the repeatability of your results
rng(’shuffle’)seeds the random number generator based on the current time
sprintf
writing formatted data into the stringsprintf(’format’,variable1, variable2,...)
’formatspec’: text composed of
- Words,spaces,numbers
- “%flags”,replaced by the value of variables,e.g.’
%d’,’%f’ - Special characters, e.g’
\n\t’
recursion
the process of repeating items in a self-similar way
1 | function result = factorial_recurcive(n) |
Good about Recursion Recursion:
usually leads to compact and elegant code
Bad about Recursion:
- Infinite recursion if no base case identified
- No guarantee of convergence if not a smaller problem
- Excessive memory requirements
- excessive recomputation
So, recursion+memorization!
data types
![[Pasted image 20240530112114.png]]
- int: int8, int16, int32 and int64
- uint: unit8, uint16, uint32 and uint64
- floating point: mantissa and exponent
type-related function
Type of a varible: whos, isreal, isinf, isnumeric, isnan, isfinite
Numeric conversions: cast(a, ‘type’), uint8(a)
useful string functions: isletter, strncmpi(s1, s2, n), isspace, strrep(s1, s2, s3), strcmp(s1, s2), strfind(s1, s2),strcmpi(s1,s2), num2str(a,’format’), strncmp(s1,s2,n), str2num(s)
![[Pasted image 20240530112604.png]]
struct
Struct has fields, not elements
Access its fields by fieldName, not by index
Fields in the same struct can have different types
example:
1 | student.name=’Allan’; |
