Matlab Learning Notes

Docs: MATLAB Help Center

How to filter a table

1
theTable(theTable.VariableName == 0, :);

returns a table that contains every row in theTable whose VariableName == 0.

Remove Rows from Table

Docs

This removes rows with row id 3,5,7 from the table.

1
table([3,5,7],:)=[];

Things Unique to MATLAB

Cell Array

Docs

A cell array is a data type with indexed data containers called cells, where each cell can contain any type of data.

Use A{1} to access a cell.

Vectorization

Instead of write:

1
2
3
4
5
6
7
8
a = input('');
for i = 1:size(a, 1)
for j = 1:size(a, 2)
if (a(i, j) > 5)
a(i, j) = sqrt(a(i, j));
end
end
end

Write: (use logic array as mask)

1
2
3
a = input('');
b = a > 5;
a(b) = sqrt(a(b));

This is because logical array can serve as a mask for arithmetic operations.

What if we want all the elements greater than 5 to be sqrt and the rest be sqr.

Then write:

1
2
3
4
5
6
a = input('');
b = a > 5;
c = ~b;
a(b) = sqrt(a(b));
a(c) = a(c).^2;
disp(a);

Function Handle (a unique class)

Docs: function handle

1
2
3
4
5
6
7
8
9
10
11
12
13
>> f = @(x) x^2-3*x+1

f =

function_handle with value:

@(x)x^2-3*x+1

>> f(1)

ans =

-1

Add Fonts to MATLAB

Reference: Can I add custom fonts to my MATLAB Desktop in Preferences?

Basically, copy ttf font files to \matlabRoot\sys\java\jre\win64\jre\lib\fonts, restart MATLAB, and choose the font in the MATLAB preferences.

Erasing a Column or Row

1
a(:,3)=[];

Array Initialization

1
2
3
4
5
6
a=zeros(5,2);
a=rand(5,2);
a=ones(5,2);
a=[1:5]; %initial:end
a=[1:2:5]; %initial:step:end
disp(a);

[;] and [,] | Merge Arrays

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
>> x=[3;2;6;8]

x =

3
2
6
8

>> y=[4;1;3;5]

y =

4
1
3
5

% merge several arrays in a vertical way; use ',' to merge them in a horizontal way
>> y=[y;sum(x)]

y =

4
1
3
5
19

( : , : ) | Array Indexing

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
% anyArrayNameYouLike(startRow:endRow,startColumn:endColumn)
>> y(1:4,:)

ans =

4
1
3
5

>> y=ans

y =

4
1
3
5

.^ .* ./ | Element-wise Calculations

1
2
3
4
5
6
7
8
9
% use '.' before calculation marks to perform element-wise calculations rather than matrix calculations
>> x.^y

ans =

81
2
216
32768

‘ | Conjugate Transpose a Matrix

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
>> x'

ans =

3 2 6 8

>> w=sum(x.*y)

w =

72

>> x'*y-w

ans =

0

>> A=[1,3,5]

A =

1 3 5

>> B=[3,6,9]

B =

3 6 9

If complex number is involved and you simply want to transpose a matrix without turning complex numbers into its conjugate complex number, use .' instead.

union(A,B) | Merge Multiple Arrays without Repetition

1
2
3
4
5
>> union(A,B)

ans =

1 3 5 6 9

Functions

array2table | Convert homogeneous array to table

Docs

format | Set output display format

1
2
format default
format rational

groupcounts() | Count group numbers satisfying certain conditions

Docs

linspace() | Generate linearly spaced vector

1
y = linspace(x1,x2,n)

generates n points. The spacing between the points is $(x2-x1)/(n-1)$.

find() | Find Index of Element in Array

Reference

1
2
a=[3,1,2]
find(a==1) = 2

If you want to find index of string in a cell array, check out this page

readtable() | Read Full Table from File

Docs

1
table=readtable('fileName','ReadVariableNames',true);

log() | ln

1
log(e)=1;

fopen() | Low Level Input Output File

Docs

Output: use function fprintf; use feof to determine whether reach the end of the file.

Input: use function fscanf, fgetl or fgets.

readmatrix() | Read Matrix from File

Docs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
type basic_matrix.txt

6,8,3,1
5,4,7,3
1,6,7,10
4,2,8,2
2,7,5,9

M = readmatrix('basic_matrix.txt')

M = 5×4

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

importdata() | Import Data from File

Docs

This function can intelligently load the file based on the extension name.

1
A = importdata('ngc6543a.jpg');

reverse() | Reverse String

1
reverse('123')='321'

flip() | Flip Array

1
flip([1 2;3 4])=[3 4;1 2]

fprintf() | Formatted Output

Docs

Use %% to print %

This function can also output to file.

sort() | Sort

Docs

By default, sort sorts the array from small to large.

Use sort(A,'descend') to sort the array from large to small.

numel(A) | Get Row*Col of A

Docs

subplot(n,m,p) | Plot Several Image Together

Docs

reshape(A, sz1, sz2 … szN) | Reshape Array

Docs

fit(x,y,fitType) | Fit Curve or Surface to Data

Docs on fit()

Docs on coeffvalues()

1
2
3
4
5
x=[1;2;3];
y=[1.09;2.2;3.3];
sf=fit(x,y,'poly1');
disp(sf);
disp(coeffvalues(sf));

Output:

1
2
3
4
5
6
 Linear model Poly1:
sf(x) = p1*x + p2
Coefficients (with 95% confidence bounds):
p1 = 1.105 (1.068, 1.142)
p2 = -0.01333 (-0.09257, 0.0659)
1.1050 -0.0133

isequal(A1,A2,A3,…,An) | Determine Array Equality

Simple to understand.

To be noticed, string and char is also a type of array.

isa(variable,char) | Whether a Variable is a Certain Type

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
>> s=1234

s =

1234

>> isa(s,'double')

ans =

logical

1

>> isa(s,'string')

ans =

logical

0

class(variable) | Get Class/Type of a Variable

1
2
3
4
5
6
7
8
9
10
11
>> s=1234

s =

1234

>> class(s)

ans =

'double'

prod(array) | Product of an Array

1
2
3
4
5
>> prod([1,2,3,4])

ans =

24

primes(n) | Primes

1
2
p = primes(n) 
%returns a row vector containing all the prime numbers less than or equal to n. The data type of p is the same as that of n.

strfind(str, substr) | Locate substr in str

1
2
3
4
5
6
7
>> str = 'Find the starting indices of substrings in a character vector';
>> k = strfind(str,'in')

k =

2 15 19 36 41

input(prompt, argument) | Input

1
2
3
4
5

someVariableName=input(prompt)
% where prompt is a string (can be empty) that pops up before user input
% If you want to input a string, use:
someStringVariableName=input("","s")

disp(array) | Output

1
2
x=[1,2]
disp(x)

~ || && | Logic Calculation

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
>> ~1

ans =

logical

0

>> 1 && 0

ans =

logical

0

>> 1 || 0

ans =

logical

1

mod(n, m) fix(n) | Take the Round and Mod

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
% mod
>> mod(5,2)

ans =

1

% fix: towards 0
>> fix(1.1)

ans =

1

>> fix(-1.1)

ans =

-1

length(array) strlength(string) | The Length of an Array and a String

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
>> x=[3;2;6;8]

x =

3
2
6
8

>> length(x)

ans =

4

>> s="This is a string"

s =

"This is a string"

% Also, I find length() can do the job as well
>> strlength(s)

ans =

16

% Use '' to wrap things that is not logically a string.
>> s='GCTA' % a DNA sequence

s =

'GCTA'

[min, max]=bounds(array) | Get Min and Max in an Array

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
>> A

A =

1 3 5

>> [minA,maxA]=bounds(A)

minA =

1


maxA =

5

clc | Clear Screen

1
>> clc

randi() | Get Random Int

Docs: randi()

1
2
3
4
5
6
7
8
9
10
11
>> randi([1,3])

ans =

3

>> randi([1,10],1,5)

ans =

6 2 7 3 7

Docs: 2-D and 3-D Plots

1
2
3
4
5
6
7
8
9
x = linspace(0,2*pi);
y = sin(x);
plot(x,y)
xlabel("x")
ylabel("sin(x)")
title("Plot of the Sine Function")
plot(x,y,"r--") % plot using red dashed line
plot(x,y,"r:o")
plot(x,y,"b:*")

Notice that the titles and labels that you defined for the first plot are no longer in the current figure window. By default, MATLAB clears the figure each time you call a plotting function, resetting the axes and other elements to prepare the new plot.

To add plots to an existing figure, use hold on. Until you use hold off or close the window, all plots appear in the current figure window.

1
2
3
4
5
6
7
8
9
10
11
x = linspace(0,2*pi);
y = sin(x);
plot(x,y)

hold on

y2 = cos(x);
plot(x,y2,":")
legend("sin","cos")

hold off

Docs: Programming and Scripts

struct | Similar to struct in C

Docs

1
2
s.a = 1;
s.b = {'A','B','C'}

or

1
s = struct('a',1,'b','Bob')

Write Custom Functions

1
2
3
4
% y are outputs and x are input
function [y1,...,yN] = myfun(x1,...,xM)
% here scripts
end

loop, if

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
N = 100;
f(1) = 1;
f(2) = 1;
for i = 3:N % for loop
f(i) = f(i - 1) + f(i - 2);
end
f(1:10)

>> for i=1:-0.3:0
disp(i);
end
1

0.7000

0.4000

0.1000

% if elseif and else
num=randi(100)
if num<34
sz='low'
elseif num<67
sz='medium'
else
sz='high'
end % remember to add 'end' at the end of if!!!!

n = 10;
f = n;
while n > 1 % while loop
n = n-1;
f = f*n;
end
disp(['n! = ' num2str(f)])