MATLAB is an essential and convenient tool in scientific and engineering research, and it is a skill that many graduate students must master before entering school. This article will help you quickly get started with MATLAB through three main sections.
Basic Knowledge of MATLAB
1-1. Basic Operations and Functions
To perform basic mathematical operations in MATLAB, simply enter the expression directly after the prompt (>>) and press Enter. For example:
>> (5*2+1.3-0.8)*10/25
ans = 4.2000
MATLAB will store the result in a variable called ans, which represents the answer after computation and displays its value on the screen.
Tip: “>>” is MATLAB’s prompt, but in a Chinese Windows environment on a PC, this prompt may often disappear due to encoding differences. However, this does not affect the computation results in MATLAB.
We can also assign the result of the above expression to another variable x:
x = (5*2+1.3-0.8)*10^2/25
x = 42
At this point, MATLAB will directly display the value of x. From the above example, we can see that MATLAB recognizes all common mathematical operators such as addition (+), subtraction (-), multiplication (*), division (/), and exponentiation (^).
Tip: MATLAB stores all variables in double format, so there is no need for variable declaration. MATLAB also automatically manages memory usage and recycling, unlike C, where users must specify this explicitly. These features make MATLAB easy to learn and use, allowing users to focus on writing code without being distracted by software-related issues.
If you do not want MATLAB to display the computation result every time, simply add a semicolon (;) at the end of the expression, as shown below:
y = sin(10)*exp(-0.3*4^2);
If you want to display the value of variable y, just type y:
>> y
y = -0.0045
In the above example, sin is the sine function, and exp is the exponential function, both of which are commonly used mathematical functions in MATLAB.
The following table lists commonly used basic mathematical functions and trigonometric functions in MATLAB:
Summary (Commonly Used Basic Mathematical Functions in MATLAB):
abs(x): absolute value of a scalar or length of a vector
angle(z): phase angle of complex number z
sqrt(x): square root
real(z): real part of complex number z
imag(z): imaginary part of complex number z
conj(z): conjugate of complex number z
round(x): round to the nearest integer
fix(x): truncate to the nearest integer regardless of sign
floor(x): floor function, truncates positive decimals to the nearest integer
ceil(x): ceiling function, rounds up positive decimals to the nearest integer
rat(x): convert real number x to fractional representation
rats(x): convert real number x to polynomial fraction expansion
sign(x): signum function.
When x < 0, sign(x) = -1;
When x = 0, sign(x) = 0;
When x > 0, sign(x) = 1.
Summary: Commonly Used Trigonometric Functions in MATLAB:
sin(x): sine function
cos(x): cosine function
tan(x): tangent function
asin(x): inverse sine function
acos(x): inverse cosine function
atan(x): inverse tangent function
atan2(x,y): four-quadrant inverse tangent function
sinh(x): hyperbolic sine function
cosh(x): hyperbolic cosine function
tanh(x): hyperbolic tangent function
asinh(x): inverse hyperbolic sine function
acosh(x): inverse hyperbolic cosine function
atanh(x): inverse hyperbolic tangent function
Variables can also be used to store vectors or matrices and perform various operations, such as the following example of row vector operations:
x = [1 3 5 2];
y = 2*x + 1
y = 3 7 11 5
Tip: Rules for Naming Variables
1. The first letter must be an English letter 2. No spaces are allowed between letters 3. A maximum of 19 letters is allowed; MATLAB will ignore any excess letters
We can freely change, add, or delete elements of a vector:
y(3) = 2 % Change the third element
y = 3 7 2 5
y(6) = 10 % Add the sixth element
y = 3 7 2 5 0 10
y(4) = [] % Delete the fourth element,
y = 3 7 2 0 10
In the above example, MATLAB will ignore all text after the percent sign (%), so the text after the percent sign can be considered comments.
MATLAB can also retrieve an element or a portion of a vector for computation:
x(2)*3 + y(4) % Retrieve the second element of x and the fourth element of y for computation
ans = 9
y(2:4)-1 % Retrieve the second to fourth elements of y for computation
ans = 6 1 -1
In the above example, 2:4 represents a vector consisting of 2, 3, and 4.
If you have questions about the usage of MATLAB functions, you can always use help for online support: help linspace
Summary: MATLAB Query Commands
help: used to query the usage of known commands. For example, if you know inv is used to calculate the inverse matrix, typing help inv will provide information about the inv command. (Typing help help will show the usage of help, try it out!) lookfor: used to find unknown commands. For example, to find the command for calculating the inverse matrix, you can type lookfor inverse, and MATLAB will list all commands related to the keyword inverse. After finding the required command, you can use help to further find its usage. (lookfor actually compares the first annotation line of all M files in the search path with the keyword, see below for details.)
Transposing a row vector yields a column vector:
z = x’
z = 4.0000
5.2000
6.4000
7.6000
8.8000
10.0000
Regardless of whether it is a row vector or a column vector, we can use the same functions to find the number of elements, maximum value, minimum value, etc:
length(z) % Number of elements in z
ans = 6
max(z) % Maximum value in z
ans = 10
min(z) % Minimum value in z
ans = 4
Summary: Common Functions Applicable to Vectors:
min(x): minimum value of the elements in vector x
max(x): maximum value of the elements in vector x
mean(x): average value of the elements in vector x
median(x): median value of the elements in vector x
std(x): standard deviation of the elements in vector x
diff(x): difference between adjacent elements in vector x
sort(x): sort the elements in vector x
length(x): number of elements in vector x
norm(x): Euclidean length of vector x
sum(x): total sum of the elements in vector x
prod(x): total product of the elements in vector x
cumsum(x): cumulative sum of the elements in vector x
cumprod(x): cumulative product of the elements in vector x
dot(x, y): dot product of vectors x and y
cross(x, y): cross product of vectors x and y (most vector functions can also be applied to matrices, see below).
To input a matrix, you must add a semicolon (;) at the end of each row, as shown below:
A = [1 2 3 4; 5 6 7 8; 9 10 11 12];
A =
1 2 3 4
5 6 7 8
9 10 11 12
Similarly, we can perform various operations on matrices:
A(2,3) = 5 % Change the value at the second row, third column
A =
1 2 3 4
5 6 5 8
9 10 11 12
B = A(2,1:3) % Retrieve part of matrix B
B = 5 6 5
A = [A B’] % Add B transposed as a column vector to A
A =
1 2 3 4 5
5 6 5 8 6
9 10 11 12 5
A(:, 2) = [] % Delete the second column ( : represents all rows)
A =
1 3 4 5
5 5 8 6
9 11 12 5
A = [A; 4 3 2 1] % Add a fourth row
A =
1 3 4 5
5 5 8 6
9 11 12 5
4 3 2 1
A([1 4], 🙂 = [] % Delete the first and fourth rows ( : represents all columns)
A =
5 5 8 6
9 11 12 5
These various matrix processing methods can be iteratively applied to produce various unexpected effects, depending on your ingenuity and creativity.
Tip: In MATLAB’s internal data structure, every matrix is an array that is column-oriented. Therefore, for accessing matrix elements, we can use one-dimensional or two-dimensional indexing. For example, in the matrix A above, the element at the second row, third column can be written as A(2,3) (two-dimensional indexing) or A(6) (one-dimensional indexing, referring to the sixth element after stacking all columns).
Additionally, if you want to reshape a matrix, you can use the reshape command:
B = reshape(A, 4, 2) % 4 is the number of rows in the new matrix, 2 is the number of columns in the new matrix
B =
5 8
9 12
5 6
11 5
Tip: A(:) stacks each row of matrix A into a column vector, which is also how MATLAB internally stores variables. In the previous example, reshape(A, 8, 1) and A(:) both produce an 8×1 matrix.
MATLAB can execute multiple commands simultaneously, as long as they are separated by commas or semicolons:
x = sin(pi/3); y = x^2; z = y*10;
z =
7.5000
If a mathematical operation is too long, you can extend it to the next line with three dots:
z = 10*sin(pi/3)* …
sin(pi/3);
If you want to view the variables present in the workspace, you can type who:
who
Your variables are:
testfile x
These are user-defined variables. To know the detailed information about these variables, you can type:
whos
Name Size Bytes Class
A 2×4 64 double array
B 4×2 64 double array
ans 1×1 8 double array
x 1×1 8 double array
y 1×1 8 double array
z 1×1 8 double array
Grand total is 20 elements using 160 bytes
Using clear can delete variables from the workspace:
clear A
A
??? Undefined function or variable ‘A’.
Additionally, MATLAB has some permanent constants that, while not visible in the workspace, can be directly accessed, such as:
pi
ans = 3.1416
The following table lists commonly used permanent constants in MATLAB.
Summary: Permanent Constants in MATLAB
i or j: basic imaginary unit
eps: system floating-point precision
inf: infinity, e.g., 1/0
nan or NaN: Not a number, e.g., 0/0
pi: pi ( = 3.1415926…)
realmax: largest number that the system can represent
realmin: smallest number that the system can represent
nargin: number of input arguments for a function
nargout: number of output arguments for a function
1-2. Repeating Commands
The simplest repeat command is the for-loop, which has the basic form:
for variable = matrix;
operation;
end
The value of the variable will be sequentially assigned to each row of the matrix to execute the operations between for and end. Therefore, unless there are unexpected circumstances, the number of times the operation is executed will equal the number of rows in the matrix.
For example, the following command will produce a harmonic sequence of length 6:
x = zeros(1,6); % x is a zero matrix of length 6
for i = 1:6,
x(i) = 1/i;
end
In the above example, the matrix x is initially a zero matrix of length 6, and in the for-loop, the value of variable i is sequentially set from 1 to 6, thus the value of the i-th element in matrix x is set to 1/i. We can display this sequence as fractions:
format rat % Use fractions to represent values
disp(x)
1 1/2 1/3 1/4 1/5 1/6
For-loops can be nested; the following example produces a 6×6 Hilbert matrix h, where the element at the i-th row and j-th column is:
h = zeros(6);
for i = 1:6,
for j = 1:6,
h(i,j) = 1/(i+j-1);
end
end
disp(h)
1 1/2 1/3 1/4 1/5 1/6
1/2 1/3 1/4 1/5 1/6 1/7
1/3 1/4 1/5 1/6 1/7 1/8
1/4 1/5 1/6 1/7 1/8 1/9
1/5 1/6 1/7 1/8 1/9 1/10
1/6 1/7 1/8 1/9 1/10 1/11
Tip: Preallocating Matrices In the above example, we used zeros to preallocate an appropriately sized matrix. If a matrix is not preallocated, the program can still run, but MATLAB will have to dynamically increase (or decrease) the size of the matrix, thus reducing the execution efficiency of the program. Therefore, when using a matrix, if you can know its size in advance, it is best to preallocate the required memory (i.e., the matrix) using commands like zeros or ones.
In the following example, the for-loop lists the sum of squares of each row of the previously generated Hilbert matrix:
for i = h,
disp(norm(i)^2); % Print the sum of squares of each row
end
1299/871
282/551
650/2343
524/2933
559/4431
831/8801
In the above example, each time the value of i corresponds to a row of matrix h, making the command particularly concise.
Another commonly used repeat command is the while-loop, which has the basic form:
while condition;
operation;
end
This means that as long as the condition holds true, the operation will be executed repeatedly. For example, the previous harmonic sequence can be rewritten using a while-loop as follows:
x = zeros(1,6); % x is a zero matrix of length 6
i = 1;
while i <= 6,
x(i) = 1/i;
i = i + 1;
end
format short
1-3. Logical Commands
The simplest logical command is if, …, end, which has the basic form:
if condition;
operation;
end
if rand(1,1) > 0.5,
disp(‘Given random number is greater than 0.5.’);
end
Given random number is greater than 0.5.
1-4. Grouping Multiple Commands into One M File
If you want to execute a large number of MATLAB commands at once, you can store these commands in a file with the m extension and simply type the main file name at the MATLAB prompt. These files containing MATLAB commands are all referred to as M files. For example, if an M file named test.m contains a series of MATLAB commands, you can execute all the commands by typing test:
pwd % Display the current directory
ans =
D:\MATLAB5\bin
cd c:\data\mlbook % Enter the directory where test.m is located
type test.m % Display the contents of test.m
% This is my first test M-file.
% Roger Jang, March 3, 1997
fprintf(‘Start of test.m!\n’);
for i = 1:3,
fprintf(‘i = %d —> i^3 = %d\n’, i, i^3);
end
fprintf(‘End of test.m!\n’);
test % Execute test.m
Start of test.m!
i = 1 —> i^3 = 1
i = 2 —> i^3 = 8
i = 3 —> i^3 = 27
End of test.m!
Tip: The first annotation line (H1 help line) in test.m is a comment that makes the program easier to understand and manage. It is particularly important to note that the first annotation line is usually used to briefly describe the function of this M file so that lookfor can find this M file by comparing keywords. For example, the first annotation line of test.m contains the word test, so if you type lookfor test, MATLAB will list all M files that contain the word test in their first annotation line, including test.m.
Strictly speaking, M files can be further divided into scripts and functions. The aforementioned test.m is a script, which has the same effect as entering the commands one by one, so variables defined in the script can be directly used in the workspace, and variables set in the script will also be visible in the workspace. Functions require input arguments and output arguments to pass information, similar to functions in C or subroutines in FORTRAN. For example, to compute the factorial of a positive integer, we can write a MATLAB function and save it as fact.m:
function output = fact(n)
% FACT Calculate factorial of a given positive integer.
output = 1;
for i = 1:n,
output = output*i;
end
Where fact is the function name, n is the input argument, output is the output argument, and i is a temporary variable used in this function. To use this function, simply type the function name and the appropriate input argument value:
y = fact(5)
y = 120
(Of course, before executing fact, you must first navigate to the directory where fact.m is located.) When executing fact(5), MATLAB enters a temporary workspace, sets the value of variable n to 5, and then performs all internal calculations. All variables generated during the internal calculations (including input argument n, temporary variable i, and output argument output) exist in this temporary workspace. After the computation is complete, MATLAB assigns the final value of output to the upper-level variable y and clears this temporary workspace and all its variables. In other words, when calling a function, you can only control the function’s input through input arguments and obtain the function’s output through output arguments, but all temporary variables will disappear once the function ends, and you cannot access their values.
Tip: The factorial function mentioned earlier is purely for illustrating the concept of MATLAB functions. If you actually want to compute the factorial of a positive integer n (i.e., n!), you can directly write it as prod(1:n), or simply call the gamma function: gamma(n-1).
MATLAB functions can also be recursive, meaning a function can call itself.
For example, n! = n*(n-1)!, so the previous factorial function can be rewritten recursively:
function output = fact(n)
% FACT Calculate factorial of a given positive integer recursively.
if n == 1, % Terminating condition
output = 1;
return;
end
output = n*fact(n-1);
When writing a recursive function, it is essential to include a terminating condition; otherwise, the function will keep calling itself indefinitely until the computer’s memory is exhausted. In the above example, n==1 satisfies the terminating condition, and we directly set output to 1 without calling the function again.
1-5. Search Path
In the previous section, the directory of test.m is d:\mlbook. If you do not enter this directory first, MATLAB will not find the M file you want to execute. If you want MATLAB to execute test.m no matter where you are, you must add d:\mlbook to MATLAB’s search path. To check MATLAB’s search path, type path:
path
MATLABPATH
d:\matlab5\toolbox\matlab\general
d:\matlab5\toolbox\matlab\ops
d:\matlab5\toolbox\matlab\lang
d:\matlab5\toolbox\matlab\elmat
d:\matlab5\toolbox\matlab\elfun
d:\matlab5\toolbox\matlab\specfun
d:\matlab5\toolbox\matlab\matfun
d:\matlab5\toolbox\matlab\datafun
d:\matlab5\toolbox\matlab\polyfun
d:\matlab5\toolbox\matlab\funfun
d:\matlab5\toolbox\matlab\sparfun
d:\matlab5\toolbox\matlab\graph2d
d:\matlab5\toolbox\matlab\graph3d
d:\matlab5\toolbox\matlab\specgraph
d:\matlab5\toolbox\matlab\graphics
d:\matlab5\toolbox\matlab\uitools
d:\matlab5\toolbox\matlab\strfun
d:\matlab5\toolbox\matlab\iofun
d:\matlab5\toolbox\matlab\timefun
d:\matlab5\toolbox\matlab\datatypes
d:\matlab5\toolbox\matlab\dde
d:\matlab5\toolbox\matlab\demos
d:\matlab5\toolbox\tour
d:\matlab5\toolbox\simulink\simulink
d:\matlab5\toolbox\simulink\blocks
d:\matlab5\toolbox\simulink\simdemos
d:\matlab5\toolbox\simulink\dee
d:\matlab5\toolbox\local
This search path will vary depending on the installed toolboxes. To find out where a specific command is located in the search path, you can use the which command:
which expo
d:\matlab5\toolbox\matlab\demos\expo.m
Clearly, c:\data\mlbook is not in MATLAB’s search path, so MATLAB cannot find the test.m M file:
which test
c:\data\mlbook\test.m
To add d:\mlbook to MATLAB’s search path, you can use the path command:
path(path, ‘c:\data\mlbook’);
Now d:\mlbook has been added to MATLAB’s search path (type path to check), so MATLAB can now “see”
test.m:
which test
c:\data\mlbook\test.m
Now we can directly type test without needing to enter the directory where test.m is located first.
Tip: How to Automatically Set the Required Search Path When Starting MATLAB? If you have to set the required search path every time you start MATLAB, it can be quite tedious. There are two methods to automatically load user-defined search paths when MATLAB starts:
1. The default search path for MATLAB is defined in matlabrc.m (under c:\matlab or another main directory where MATLAB is installed), and MATLAB automatically executes this file each time it starts. Therefore, you can modify matlabrc.m to add new directories to the search path.
2. While executing matlabrc.m, MATLAB will also look for startup.m in the default search path. If this file exists, it will execute the commands contained within it. Therefore, we can place all commands that need to be executed when MATLAB starts (including commands to change the search path) in this file.
Whenever MATLAB encounters a command (e.g., test), its processing sequence is as follows:
1. Treat test as a user-defined variable.
2. If test is not a user-defined variable, treat it as a permanent constant.
3. If test is neither a user-defined variable nor a permanent constant, check if it is an M file in the current working directory.
4. If not, check the search path for the presence of the test.m file.
5. If the test.m file cannot be found in the search path, MATLAB will beep and display an error message.
The following introduces various commands related to MATLAB’s search path.
1-6. Saving and Loading Data
Some calculations can be time-consuming, so we usually hope to save the computed results to a file for future processing. The basic command for saving variables in MATLAB is save. Without any options, save will save the variables in a binary file with the extension .mat, as follows:
save: saves all variables in the workspace to a binary file named matlab.mat.
save filename: saves all variables in the workspace to a binary file named filename.mat.
save filename x y z: saves variables x, y, z to a binary file named filename.mat.
The following is an example of using the save command:
who % List the variables in the workspace
Your variables are:
B h j y
ans i x z
save test B y % Save variables B and y to test.mat
dir % List the files in the current directory
. 2plotxy.doc fact.m simulink.doc test.m ~$1basic.doc
.. 3plotxyz.doc first.doc temp.doc test.mat
1basic.doc book.dot Go.m template.doc testfile.dat
delete test.mat % Delete test.mat
Saving variables in binary format usually results in smaller files and faster loading speeds, but the contents of the files cannot be viewed with ordinary text editors (e.g., pe2 or Notepad). If you want to see the contents of the file, you must add the -ascii option, as follows:
save filename x -ascii: saves variable x as an ASCII file named filename.
save filename x -ascii -double: saves variable x as a 16-bit ASCII file named filename.
Another option is -tab, which separates adjacent numbers in the same row with tabs.
Tip: Comparison of Binary and ASCII Files When using the save command with the -ascii option, the following occurs: the save command will not append the .mat extension to the file name.
Therefore, files ending with the .mat extension are usually MATLAB binary data files.
Unless there is a special need, we should try to save data in binary format.
The load command can load a file to retrieve the saved variables:
load filename: load will look for a file named filename.mat and load it in binary format. If filename.mat cannot be found, it will look for a file named filename and load it in ASCII format.
load filename -ascii: load will look for a file named filename and load it in ASCII format.
If loaded in ASCII format, the variable names will be the same as the file name (excluding the extension). If loaded in binary format, the original variable names can be retained, as shown in the following example:
clear all; % Clear variables in the workspace
x = 1:10;
save testfile.dat x -ascii % Save x in ASCII format to a file named testfile.dat
load testfile.dat % Load testfile.dat
who % List the variables in the workspace
Your variables are:
testfile x
Note that during the above process, since it was saved and loaded in ASCII format, a variable named testfile was generated, which is the same as the file name, and its value is identical to the original variable x.
1-7. Exiting MATLAB
There are three ways to exit MATLAB:
1. Type exit
2. Type quit
3. Directly close the MATLAB command window
Disclaimer: This article is reproduced from Zhao Yue’s WeChat public platform
To facilitate academic discussions among research friends, Yan Zhi Cheng Li has also created its own QQ group, Group 1: Full; Group 2: Full; Group 3: 585629919. Everyone is welcome to join for intense academic discussions!
The copyright of this article belongs to Yan Zhi Cheng Li. Please contact us via QQ for reprints. Please do not pirate without permission. Thank you!
Long press the image below to recognize the QR code in the image or search for the WeChat ID rationalscience to easily follow us. Thank you!