📄 matlab_tutorial.m
字号:
% Basic MATLAB tutorial for Informatics students
% Predrag Radivojac
% Indiana University School of Informatics
% Bloomington, Indiana
% predrag@indiana.edu
% Tutorial is available at
% www.informatics.indiana.edu/predrag
%***********************************************************
% 1. MATLAB Basics
%***********************************************************
% MATLAB is an interpreting programming language that supports all
% basic operations and functions like other programming languages
% (e.g. if-else structure, for loop, while loop, case-switch structure,
% break, try, catch, return, ...)
% check version of MATLAB
version
% check version of MATLAB and toolboxes
ver
% check working directory
pwd
% delete all variables from the workspace (same as only 'clear')
clear all
% clear screen
clc
% define variable 'a'
% 'a' will be displayed on the screen; semi-colon will stop printouts
a = 10
% use if, for
if (a == 4) % parentheses are not required
b = a ^ 2 % 'b' equals 'a' squared, b is printed on the screen
elseif (a ~= 10)
b = a
else
b = -a
end % note that there is only one 'end' for the whole 'for' structure
% for loop - start with 1, step is 2, end if i <= 10
for i = 1 : 2 : 10
i
end
% MATLAB supports help system through its help window, or through help statement from the
% command prompt (e.g. help case)
help case
% There is also a "lookfor" function, when we are not sure what is the exact name of
% the statement or the function. Lookfor searches for specifiec word through description
% of all available MATLAB functions e.g. "lookfor write" gives all functions that contains
% the word write in their description
% In addition, MATLAB has integrated powerful functons for elementary matrix
% manipulation and numerical linear algebra, elementary and specialized math
% functions, 2D and 3D graphic, interpolation, polynomials, Fourier transforms,
% sparse matrices, .....
% Unlike other languages it DOES NOT make executable code (a special toolbox is needed for it)
% Instead, it interprets comands of functions written in the script or inside a function.
% Function has a specific syntax and should be called.% It can have more than one input and output arguments.
% Normally, arguments are transfered by value. It is possible to pass arguments
% by reference (as common attributes for caller and the function), but you'll
% never need this...
a = 5; % 'a' is not displayed
b = 4 % 'b' is displayed
% 'operations' is a function that takes two input variables and returns two
% output variables; these two are displayed since no semi-colon is after
% 'operations'
[sum_ab, product_ab] = operations(a, b)
pause(3) % go to sleep for 3 seconds
%***********************************************************
% 2. Matrix Operations
%***********************************************************
A = [1 2 3
4 5 6
7 8 9
10 11 12]
B = [1 3 5
7 11 13
17 19 23
29 31 37]
% another way to initialize a matrix
C = [1 2 3 4; 5 6 7 8; 9 10 11 12]
D = A + B
E = A * C
F = C * B
F1 = inv(sqrt(F))
% notice the use of a dot "." BEFORE a command
A
B
G = B ./ A
G_transpose = G'
G_transpose = transpose(G)
% go to sleep until interrupted (you need to press any key in MATLAB's main window)
pause
% MATLAB is very powerful in matrix computations
% DO NOT USE for loop for matrix calculations
% THERE IS ALWAYS A FASTER WAY TO DO THINGS
% dimensions of the matrix 'A'
[num_rows, num_cols] = size(A)
% or only the number or rows (first dimension)
num_rows = size(A, 1)
% or only the number or columns (second dimension)
num_cols = size(A, 2)
A
sum(A) % sumation performed over columns
sum(A, 1) % same as above
sum(A, 2) % sum of rows
sum(sum(A)) % sum all elements in the matrix
% the use of column operator is VERY important in MATLAB
% for instance, let's separate one COLUMN
A
for i = 1 : size(A, 2)
A_column = A(:, i)
end
% separate one ROW
A
for i = 1 : size(A, 1)
A_row = A(i, :)
end
% special matrix functions
diagonal_matrix = diag([1 2 3 4])
all_zeros = zeros(3, 4)
all_ones = ones(4, 2)
identity_matrix = eye(4)
%***********************************************************
% 3. Operations on Strings
%***********************************************************
% define two arbitrary strings
s1 = 'WBuCDefg3'
s2 = 'AAAaAAA'
% concatenate two strings
s = [s1 s2]
% this works with matrices too
A
a1 = [9 8 7 6]'
A1 = [A a1]
a1 = [0 0 0 0]
A1 = [A1; a1]
% back to strings, let's find the beginning of the substring 'AaA' in s
pos = findstr('AAA', s)
% let's form a cell array of strings... (note curly braces for cell arrays)
S{1} = s1
S{2} = s2
S{3} = s
% ... and find all that start with 'AAA'
pos = strmatch('AAA', S)
% ... now find only exact matches (shouldn't be any!)
pos = strmatch('AAA', S, 'exact')
% compare two strings, a standard operation
strcmp(s1, s2)
% check if a variable is a string
isstr(s1) % this IS a string
isstr(S) % this is NOT a string (it is a cell array of strings)
%***********************************************************
% 4. Basic Statistics and Set Operations
%***********************************************************
A
mean_A_col = mean(A) % mean over columns
mean_A_row = mean(A, 2) % mean over rows
std_A_col = std(A) % standard devaition
std_A_row = std(A, [], 2) % standard deviation ([] MUST be here - check help for details)
median_A_col = median(A, 1) % median
median_A_row = median(A, 2) % median
% now, switch to set operations
a = [1 2 3 4 5 6 7]
b = [2 4 6 8 10 12]
% find intersection of the two sets (will be a sorted array)
c = intersect(a, b)
% find union of the two (will be a sorted array)
c = union(a, b)
% find difference of the two (note: it is a directional operation)
c = setdiff(a, b)
%***********************************************************
% 5. Find Function, a very useful function
%***********************************************************
c
% find all indices where components of vector c are greater than 3
pos = find(c > 3)
% let's do a more complicated one
c = union(a, b)
pos = find(c > 3 & mod(c, 2) == 0) % greater than 3 and even ('&' is logical AND)
% let's change all elements found before
% note that we are indexing using vector 'pos'
c(pos) = 999
% instrad of logical AND use logal OR
pos = find(c > 3 | mod(c, 2) == 0) % greater than 3 or even
c(pos) = 555
%***********************************************************
% 6. Input/Output
%***********************************************************
% clear screen
clc
% check what variable we have in memory
who
% check what variable we have in memory (more detailed)
whos
% check if matrix A is in the workspace
whos A
% save specified variables into a specified file in ascii format
E
save ascii_matrix.txt E -ascii
% save specified variables into a specified file in the binary (MATLAB-specific) format
% default extension is *.mat
save bin_matrices A B C
% to save ALL variables, write only a file name. All variables in scope will be saved
save binary_all
clear A
whos % 'A' is not listed (if it is we should contact MathWorks!!!)
clear all % delete all variables in scope
clc % clear screen
whos % you should see an empty list!
% load variable 'A' from a *.mat file
load binary_all A
whos
% load all variables from a *.mat file
load binary_all
whos
% load from an ASCII fileE_matrix = load('ascii_matrix.txt')
% or
load ascii_matrix.txt
E_matrix = ascii_matrix
E
% To read from general binary files, functions fopen, fread etc. have to be used
% ececute an external command (symbol "!" indicates OS command)
!copy ascii_matrix.txt copy_of_ascii_matrix.txt
% delete a file through MATLAB
delete('copy_of_ascii_matrix.txt');
% now, make it again using command 'dos' (for unix systems use 'unix')
dos('copy ascii_matrix.txt copy_of_ascii_matrix.txt');
% eval command, useful in many cases (here just to delete a file, system command again)
file_to_delete = 'copy_of_ascii_matrix.txt';
eval(['! del ' file_to_delete]);
% if you don't want to see operating system displays use 'system' command
% 's' will be the status and 'w' will be OS output
[s, w] = system('dir');
display(w); % see what's in the current directory
%***********************************************************
% 7. Graphics
%***********************************************************
% define vector t (to indicate time)
t = 0 : 0.1 : 5
x = sin(pi * t) + 0.1 * t;
y = cos(pi * t) - 0.2 * t;
plot(t, x);
plot(t, y);
% plot x vs. y
plot(x, y); % plots 'y' as a function of 'x'
hold on % enables plotting one figure over another
plot(x, y, 'r*'); % plots blue stars instead of line
% play a bit more with x, y, and z
figure; % starts a new (empty) figure
z = 2 * t;
plot3(x, y, z, 'm-d'); % shows magenta diamonds in addition to line
% try a 3-D function (example from MATLAB's Demo)
z = peaks(25);
surfl(z);
shading interp;
colormap(pink);
% Other nice graphic functions imagesc, meshgrid, ...
% use HELP for these commands
%***********************************************************
% 8. Some Useful Functions, New and Revisited
%***********************************************************
A = [0 7 1 5 0
1 7 4 6 1
4 3 9 1 5
8 9 4 5 0
9 3 3 5 2
0 1 4 9 3
7 7 7 9 9
8 10 7 5 3
7 2 9 8 3
10 4 8 7 4]
A1 = sort(A) % SORT each column separately
A2 = sort(A, 2) % SORT each row separately
% FIND all rows (examples) where the values in
% second columen are greater than 5
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -