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
2
num1=int32([-20,20]); % a (1, 2) array
num2=cast(num1,'uint32'); % converse type of the number

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
2
3
4
5
c='Welcome to VG101';  % char
str="Welcome to VG101"; % string
% abs(s) ASCII code
% char(97) generate code from ASCII code
% length(str) length of string

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
2
3
4
5
clearvars, clc; %clear all of the varibles and the command lines
number1 = input(’Input a number: ’); %input: prompt for user input
number2 = input(’Input a number: ’);
numbers = number1 + number2;
disp(numbers); % disp: display value of a variables

arrays

initialzation

Array initialization: manualorviafunction

1
2
array_example_1D=[1,2,3]  
array_example_2D=[1,2,3;4,5,6;7,8,9] array_example_function=zeros(5,1)%rand(),ones()

Colon operator: initial : step: end

1
2
colon_example_nostepsize=[1:5] 
colon_example_with_stepsize=[1:2: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 to newsize
  • sum: sum(A) sum up all the elements in A
  • det(A): calculate the determinant
  • eig(A): calculate the eigenvalue and eigenvector

matrix

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
A = [1,2,3,4,5,6,5,4,6] 
B = 1:2:9 %第二个参数为步长,不可缺省
B = 1:3:9
C = repmat(B,3,2) %重复执行3行2列
D = ones(2,4) %生成一个2行4列的全1矩阵

% 矩阵运算
A = [1 2 3 4; 5 6 7 8]
B = [1 1 2 2; 2 2 1 1]
C = A + B
D = A - B
E = A * B'
F = A .* B % .*表示对应项相乘
G = A / B %相当于A*B的逆 G*B = A G*B*pinv(B) = A*pinv(B) G = A*pinv(B),相当于A乘B
H = A ./ B % ./表示对应项相除

% 矩阵下标
A = magic(5)
B = A(2,3)
C = A(3,:) % :为取全部,那么这条语句表示取第三行
D = A(:,4) %取第四列
[m,n] = find(A > 20) %找到大于20的序号值/矩阵 %取的是索引值

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”
  • 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
2
3
4
5
6
7
a{1,1} =[137;206;051]; 
a{1,2} =’This is a text string’;
a{2,1} =[3+4*i5; −10*i 34*i];
a{2,2} =[]; 5 a=cell(2,2); % preallocating first and assignment then
b={[1,2], 17, [2;4]; 34*i, ’Hello’, zeros(3)};
c=b{1,1}%addressing content inside cell (1,1)
c=b{1,1}(1) % addressing subsets of a cell’s content

logic operator

normal operator

Operator Description
&& Short circuit logical AND
|| Short circuit logical OR
& Bitwise logical AND
| Bitwise logical OR
example:
1
2
3
x = (1 > 2) && (3 > 2)
x = (1 > 2) || (3 > 2)
[1 2 3] & [2 3 0 ] % [0 2 0]

order of precedence:
![[Pasted image 20240530100251.png]]

if statement

1
2
3
if <expression>
<statements>
end

example:

1
2
3
4
5
a = 10; 
if a < 20
fprintf('a is less than 20' );
end
fprintf('value of a is : %d', a);

if-else statement

1
2
3
4
5
6
7
8
9
if expression1
block1
elseif expression2
block2
elseif expression3
block3
else
block4
end

switch-case-end statement

1
2
3
4
5
6
7
8
switch <num/strings>
case <num/strings>
<statements>
case <num/strings>
<statements>
...
otherwise
<statements>

exception handling machanism

1
2
3
4
5
try
statement block1
catch
statement block2
end

for loop

1
2
3
for i = <initial value> : <step length>: <end value>
<statements>
end

while loop

1
2
3
while <boolean expression>
statements
end

example:

1
2
3
4
5
while 1
myView(x);
[x,v]=myModel(x,v,t);
pause(0.01)
end

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
2
3
4
5
i=0;
for t=0:0.01:10
i=i+1;
y(i)=sin(t);
end

vectorization:

1
2
t=0:0.01:10;
y=sin(t);

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
2
3
4
5
function [out_arg1, out_arg2] = function_name(in_arg1, in_arg2)
% FUNCTION_NAME explainations
% docstrings
statements
end

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 m and M: 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 string
sprintf(’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
2
3
4
5
6
7
function result = factorial_recurcive(n)
if n~=1
result = n*factorial_recursive(n-1);
else
result = 1;
end
end

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]]

  1. int: int8, int16, int32 and int64
  2. uint: unit8, uint16, uint32 and uint64
  3. floating point: mantissa and exponent

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
2
3
4
5
6
7
student.name=’Allan’; 
student.addr=’440’;
student.grade=[788];
student(2).name=’Bob’;
student(2).addr=’441’;
student(2).grade=[10510];
str_array=struct(’name’,’Allan’,’addr1’,’440’,’grade’,100)