MATLAB basic

What is Matlab?
Matlab Screen
Variables, array, matrix, indexing Operators (Arithmetic, relational, logical ) Display Facilities
Flow Control
Using of M-File
Writing User Defined Functions Conclusion

Variables

  • No need for types. i.e.
    int a;
    double b;
    float c;

  • All variables are created with double precision unless specified and they are matrices.
    Example:
    x=5;
    x1=2;

a vector

1
x = [1 2 5 1]

x=
1 2 5 1 不加分号, 按下回车就输出

a matrix
x = [1 2 3; 5 1 4; 3 2 -1]; If you include “;” at the end of each statement, result will not be shown immediately

long array, matrix

1
t =1:10

t=
1 2 3 4 5 6 7 8 9 10

1
t = 2: -0.5: -1

t =
2.0000 1.5000 1.0000 0.5000 0 -0.5000 -1.0000

1
t = [1:4; 5:8]

x= 1 2 3 4
5 6 7 8

Generating Vectors from functions

1
x = zeros(1,3) 

x=
0 0 0

1
x = ones(1,3) 

x=
1 1 1

1
x = rand(1,3) 

ouput: 1 column 3 numbers
x=
0.9501, 0.2345, 0.3044

Concatenation of Matrices

1
x = [1 2], y = [4 5], z=c[0 0]

A = [x y]
1 2 4 5
B = [x ; y]
1 2
4 5

operand

.* element-by-element multiplication
./ element-by-element division
.^ element-by-element power

== Equal to
~= Not equal to
< Strictly smaller
__>__ Strictly greater
<= Smaller than or equal to >= Greater than equal to
& And operator
| Or operator

i.e.
Plot the function e-x/3sin(x) between 0≤x≤4π

  • Create an x-array of 100 samples between 0 and 4π

    1
    x = linspace(0, 4*pi, 100);
  • Calculate sin(.) of the x-array

    1
    y = sin(x);
  • Calculate e-x/3 of the x-array

    1
    y1 = exp(-x/3);
  • Multiply the arrays y and y1

    1
    y2 = y .* y1;

Plot the y2-array

1
plot(y2);

Display facilities

plot(y)
stem(y)
title(‘This is the sinus function’)
xlabel(‘x (secs)’)
ylabel(‘sin(x)’)

Control Structures

Output 1-200, the difference between each number is 3 i.e 1,4,7,10,13,16…..

For loop
for i=Index_Array
Matlab Commands;
end

1
2
3
for j=1:3:200
display(j);
end

check if the number is even

1
2
3
4
5
6
7
for i = 1:10
if mod(x(i),2) == 0
y(i) = 1;
else
y(i) = 0;
end
end

Calculate sum that can be divided by 3 in first 10 numbers

1
2
3
4
5
6
s = 0;
>> for i = 1:10
if mod(x(i),3) == 0
s = s + x(i);
end
end

while loop

while (condition)
Matlab Commands;
end

1
2
3
while ((a>3) & (b==5)) 
Some Matlab Commands;
end

Function

After write this function, run the program, MATLAB will ask you to input. Rember the function name must match the file name.

1
2
3
4
5
6
7
function out = squarer2(A, ind)
if(ind == 1)
out = A^2;
elseif (ind == 2)
out = A.^2;
end

check if a number is even, if even returns 1

1
2
3
function y = is_even(x)

y = mod(x, 2);

strcmp, strfind, fgetl

  • tf = strcmp(s1,s2) compares s1 and s2 and returns 1 (true) if the two are identical. Otherwise, strcmp returns 0 (false). Text is considered identical if the size and content of each are the same. The return result, tf, is of data type logical.

  • k = strfind(str,pattern) searches str for occurrences of pattern. The output, k, indicates the starting index of each occurrence of pattern in str. If pattern is not found, then strfind returns an empty array, []. The strfind function executes a case-sensitive search.

  • tline = fgetl(fileID) returns the next line of the specified file, removing the newline characters. fileID is an integer file identifier obtained from fopen. tline is a text string unless the line contains only the end-of-file marker. In this case, tline is the numeric value -1.

Struct

1
2
3
4
5
6
7
8
9
10
11
12
13
my_struct.name = 'My new struct'
my_struct.age = 25

class(my_struct.name) --> char
class(my_struct.age) --> double
isfield(my_struct, 'name') --> 1, because there is a name in struct

rmfield(my_struct, 'age') -->remove age
setfield(my_struct, 'gender', f) --> gender: 'f'

my_struct.contact.phone = 123456
my_struct.contact.email = person@gmail

my_struct =
name: ‘My new struct’

ans =
name: ‘My new struct’
age: 25
gender: ‘f’

my_struct.contact
ans =
phone: 123456
email: ‘person@gmail.com’

Altenative way

1
S = struct('name', 'Bob', 'email', 'bob@gmail.com')

S =
name: ‘Bob’
email: ‘bob@gmail.com’

1
2
3
4
my_cell{1} = 'hello world'  --> call mycell, it simply print hello world


my_cell{'A'} = {1 2; 3 4}; -> 2*2 matrix

Plot Data

Plot Fibonacci

1
2
3
4
y = [1,1,2,3,5,8,13,21]
x = [0.1,0.2,0.3,0.4,0.5,0.6,0.7]
plot(y)
plot(x, y)

Plot sin and cos

1
2
3
4
5
6
x = linspace(0, 2*pi, 100);
y = sin(x);
plot(x,y)
y2 = cos(x);
plot(x, y, x, y2);
plot(x, y, '-', x, y2, '.');

Add noise point

1
2
3
4
5
x = linspace(0, 2*pi, 1000);
y = 10*sin(x) + randn(1,1000);
plot(x,y)

scatter(x,y)
  • scatter is sorted, helpful in data analysis

bar chart

1
2
x = 1:10
bar(x)

Histogram

1
2
x = randn(1000,1);
>> hist(x)

Pie chart

1
2
x = 1:5;
pie(x)

File I/O

1
2
3
4
csvread()
csvwrite()
save()
load()

subplots, 3D plot

1
2
3
4
5
6
7
8
9
x = linspace(0, 2*pi, 100);
y = sin(x)
z = y + randn(1,100);
plot(x,z,x, y)
subplot(2,1,1)
plot(x,y)

subplot(2,1,2); --> print 2 rows, 1 column
plot(x,z)

3D plot

1
2
3
4
z = randn(100,100);
size(z)
surf(z)
contour(z) --> 2d visualization

Title and label

1
2
3
title('A plot of sin(x)')
xlabel('my label for x-axis')
ylable('my lable for y-axis')

Complete code to generate two graphs for sinx and cos x

1
2
3
4
5
6
7
8
9
10
11
12
13
x = linspace(0, 2*pi, 100);
y = sin(x);
plot(x,y)
title('A plot of sin(x)')
xlabel('my label for x-axis')
ylabel('my lable for y-axis')
z = cos(x);
subplot(2,1,1) -->first using subplot to choose a location, then plot at that place
plot(x,y)
title('sin(x)')
subplot(2,1,2)
plot(x,z)
title('cos(x)')

Sound processing

1
2
3
4
d = audioread('daliwan.wav')

[d,fs] = audioread('daliwan.wav')
sound(d,fs) -->play audio

Reverse audio

1
2
3
4
5
d2 = flipud(d);
plot(d2)

//Store reversed audio file
audiowrite('daliwan_reverse.wav', d2, fs)

2x speed

1
2
d4 = downsampel(d,2) --> d was the original audio
sound(d4,fs)

Generate random values

1
randi(10)

ans =
9

1
R = randi(10, 3)

R =
10 7 6
2 1 10
10 3 10

Histograph with random values

1
hist(rand(1000,1)