Docs: MATLAB Help Center
Table Related
How to filter a table
theTable(theTable.VariableName == 0, :);
returns a table that contains every row in theTable
whose VariableName == 0
.
Remove Rows from Table
This removes rows with row id 3,5,7 from the table.
table([3,5,7],:)=[];
Things Unique to MATLAB
Cell Array
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:
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)
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:
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
>> 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.
Array Related
Erasing a Column or Row
a(:,3)=[];
Array Initialization
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
>> 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
% anyArrayNameYouLike(startRow:endRow,startColumn:endColumn)
>> y(1:4,:)
ans =
4
1
3
5
>> y=ans
y =
4
1
3
5
.^ .* ./ | Element-wise Calculations
% use '.' before calculation marks to perform element-wise calculations rather than matrix calculations
>> x.^y
ans =
81
2
216
32768
' | Conjugate Transpose a Matrix
>> 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
>> union(A,B)
ans =
1 3 5 6 9
Functions
array2table | Convert homogeneous array to table
format | Set output display format
format default
format rational
groupcounts() | Count group numbers satisfying certain conditions
linspace() | Generate linearly spaced vector
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
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
table=readtable('fileName','ReadVariableNames',true);
log() | ln
log(e)=1;
fopen() | Low Level Input Output File
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
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
This function can intelligently load the file based on the extension name.
A = importdata('ngc6543a.jpg');
reverse() | Reverse String
reverse('123')='321'
flip() | Flip Array
flip([1 2;3 4])=[3 4;1 2]
fprintf() | Formatted Output
Use %%
to print %
This function can also output to file.
sort() | Sort
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
subplot(n,m,p) | Plot Several Image Together
reshape(A, sz1, sz2 ... szN) | Reshape Array
fit(x,y,fitType) | Fit Curve or Surface to Data
x=[1;2;3];
y=[1.09;2.2;3.3];
sf=fit(x,y,'poly1');
disp(sf);
disp(coeffvalues(sf));
Output:
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
>> s=1234
s =
1234
>> isa(s,'double')
ans =
logical
1
>> isa(s,'string')
ans =
logical
0
class(variable) | Get Class/Type of a Variable
>> s=1234
s =
1234
>> class(s)
ans =
'double'
prod(array) | Product of an Array
>> prod([1,2,3,4])
ans =
24
primes(n) | Primes
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
>> 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
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
x=[1,2]
disp(x)
~ || && | Logic Calculation
>> ~1
ans =
logical
0
>> 1 && 0
ans =
logical
0
>> 1 || 0
ans =
logical
1
mod(n, m) fix(n) | Take the Round and Mod
% 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
>> 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
>> A
A =
1 3 5
>> [minA,maxA]=bounds(A)
minA =
1
maxA =
5
clc | Clear Screen
>> clc
randi() | Get Random Int
Docs: randi()
>> randi([1,3])
ans =
3
>> randi([1,10],1,5)
ans =
6 2 7 3 7
Plot Related
Docs: 2-D and 3-D Plots
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.
x = linspace(0,2*pi);
y = sin(x);
plot(x,y)
hold on
y2 = cos(x);
plot(x,y2,":")
legend("sin","cos")
hold off
Scripts Related
Docs: Programming and Scripts
struct | Similar to struct
in C
s.a = 1;
s.b = {'A','B','C'}
or
s = struct('a',1,'b','Bob')
Write Custom Functions
% y are outputs and x are input
function [y1,...,yN] = myfun(x1,...,xM)
% here scripts
end
loop, if
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)])