Introduction to MATLAB (Part 1)

Introduction to MATLAB (Part 1)

1. Understanding MATLAB

1. Overview of MATLAB

(1) In universities across Europe and America, MATLAB has become a fundamental teaching tool for courses in linear algebra, automatic control theory, digital signal processing, time series analysis, dynamic system simulation, image processing, and more. It is a basic skill that undergraduate, master’s, and doctoral students must master.

(2) In design research institutions and industrial sectors, MATLAB is widely used to research and solve various specific engineering problems.

(3) It is foreseeable that MATLAB will play an increasingly important role in scientific research and engineering applications in our country.

2. Features of MATLAB

Powerful functionality

  • Advantages in numerical computation

  • Advantages in symbolic computation

  • Powerful 2D and 3D data visualization capabilities

Many functional functions with algorithm adaptability

  • MATLAB uses arrays as the basic unit of computation

  • It has a large number of algorithm optimization functional functions

  • Easy programming with high efficiency

Simple language with rich connotation

  • The language and writing form are very close to conventional mathematical writing

  • Comprehensive help system, easy to learn and use

Introduction to MATLAB (Part 1)

MATLAB Main Page

3. Using the Command Window

Introduction to MATLAB (Part 1)

MATLAB Command Window

“>>” along with the blinking cursor indicates that the system is ready and waiting for input;

Press the 【Enter】 key in the command line window to submit commands for execution;

Calculate 2+[(13-7)×8]÷23

Introduction to MATLAB (Part 1)

The operators used in MATLAB (such as addition, subtraction, multiplication, and division) are common in various computational programs;

The “ans” in the calculation result is an abbreviation for the English word “answer” and is a predefined variable in MATLAB;

4. Creating M Files

When a few lines of code cannot complete a task, it is necessary to create an M script, placing all the code in a single script file to be executed in order.

Click to create a new script or a new function; script files can be executed directly, while function files need to be called from a script file or the command line window before they can be used.

Introduction to MATLAB (Part 1)

The newly created function file comes with default return variables, parameters, and function names, which can be modified as needed, and the code can be edited within the function body.

Introduction to MATLAB (Part 1)

Introduction to MATLAB (Part 1)

Introduction to MATLAB (Part 1)

5. Directory and File Management

The current folder contains a detailed file list under the working directory, allowing you to run M files, load mat data, and edit files, among other functions. To run, right-click to open.

Introduction to MATLAB (Part 1)

To change the current working directory, click the drop-down arrow on the right and select again.

Introduction to MATLAB (Part 1)

In MATLAB, all files are managed through a rigorous directory folder structure. When searching for files, functions, and data, MATLAB searches according to the established search path. The order of checks is roughly as follows: first, check if the searched content is a variable; if not, check if it is a built-in function; if it is not a built-in function, check if there is an M file in the current working directory that matches the search target. If not, it will search in other specified search paths.

6. Managing Search Paths

If users have multiple files that need to interact with MATLAB or frequently need to exchange data, they can place these files on MATLAB’s search path to ensure that these files can be called from the search path. If a directory needs to run generated data and files, that directory should be set as the current working directory. If users need to modify the search path, they can enter the command pathtool in the command line window.

Users can click “Add Folder” to add a new path to the search path, and if the path to be searched also includes subfolders, click “Add and Include Subfolders”.

If users need to adjust the search order of folders already added to the search path, they can use the four buttons “Move to Top”, “Move Up”, “Move Down”, and “Move to Bottom” to change the position of the folder.

Introduction to MATLAB (Part 1)

2. Basic Knowledge of MATLAB

1. Simple Calculations in MATLAB

When variable names are not defined, data temporarily resides in ans. After defining variables, the meaning of the variables becomes clear, and the calculation process is straightforward.

Introduction to MATLAB (Part 1)

Using MATLAB, it is easy to compute and plot function curves.

Introduction to MATLAB (Part 1)

Introduction to MATLAB (Part 1)

2. Basic Operators

The order of precedence for mathematical operations in MATLAB is consistent with the usual order of precedence for mathematical processing. Exponents take precedence; multiplication and division follow; parentheses alter precedence, and expressions are evaluated from left to right.

Introduction to MATLAB (Part 1)

3. Numbers, Variables, and Expressions

Number representation:

MATLAB numbers use the conventional decimal representation, which can include decimal points and negative signs, defaulting to double-precision floating-point data.

For example: 3 -10 0.001 1.3e10 1.1343e-6

Variable naming rules:

1. Variable names and function names are case-sensitive;

2. Variable names can include letters, underscores, and numbers, but must start with a letter;

3. Variable names can contain a maximum of 63 characters.

MATLAB predefined variables:

Introduction to MATLAB (Part 1)

4. Arrays

(1) Generating Arrays

One-dimensional arrays

1. Direct input method: Separate array elements with spaces, commas, and semicolons to create a one-dimensional array.

Introduction to MATLAB (Part 1)

2. Step generation method: x = a : step : b

Introduction to MATLAB (Part 1)

3. Equally spaced linear generation method: x = linspace(a, b, n), generates n sample points in the interval from a to b.

Introduction to MATLAB (Part 1)

Two-dimensional arrays

1. Direct input method: Separate elements in the same row with commas or spaces, and separate different rows with semicolons.

Introduction to MATLAB (Part 1)

2. Call built-in functions, such as zeros, ones, rand, etc.

Introduction to MATLAB (Part 1)

3. Low-dimensional array conversion, converting low-dimensional arrays into high-dimensional arrays using functions like reshape, cat, etc.

Introduction to MATLAB (Part 1)

(2) Accessing Arrays

a=[1 2 3;4 5 6;7 8 9];

a(2,3) a(2,:) a(:,1)

Introduction to MATLAB (Part 1)

a(1,1:2) a(2,1:end-1) a(1,:)=[] a([1,3],[2,3])

Introduction to MATLAB (Part 1)

Sorting functions:

[As,idx] = sort(A)

Introduction to MATLAB (Part 1)

[As_r,idx_r] = sortrows(A)

Introduction to MATLAB (Part 1)

Sub-array search

[i,j] = find(A>0.5)

k = find(A>0.5,1)

Introduction to MATLAB (Part 1)

Maximum and minimum value search

[mx,rx] = max(A)

[mn,rx] = min(A)

Introduction to MATLAB (Part 1)

3. Programming Basics

1. Control Flow

(1) For Loop Structure

In a for loop structure, a certain loop condition must be set, and MATLAB executes the commands within the loop body according to the specified number of iterations.

for x = array

commands

end

Here, x is the loop variable, array is the condition array, and commands are the code to be executed in the loop. The number of executions of the loop body is determined by the array.

% Example of for loop structure

for n = 10 : -1 : 1

x(n) = sin(n * pi / 5);

end

x

array = ceil(rand(1,10) * 10);

for n = array

x(n) = sin(n * pi / 5);

end

x

Introduction to MATLAB (Part 1)

(2) While Loop Structure

The while loop structure performs an infinite number of iterations until the loop body meets the termination condition or reaches a certain number of iterations.

while expression

commands

end

Here, expression is the condition expression. Generally, the result of the expression is a scalar, but it can also be an array expression. When the scalar result is true, the loop body continues to execute; when the result of the expression is an array, the loop body will only execute if all elements in the array are true.

% Example of while loop structure

% Calculate the precision of floating-point number eps

EPS = 1;

num = 0;

while (EPS + 1 ) > 1

EPS = EPS / 2;

num = num + 1;

end

num

EPS = EPS * 2

Introduction to MATLAB (Part 1)

(3) If Statement Structure

The if statement structure executes different commands based on a given condition.

The if-else-end statement structure executes different command lines when the condition is true or false.

if expression

commands

end

if expression

commands1

else

commands2

end

When the expression contains multiple sub-logical expressions, MATLAB uses “short-circuit” evaluation for each expression, for example, (expression1 | expression2), where expression2 is only evaluated if expression1 is false.

% Example of if statement structure

% Find the roots of the quadratic equation a*x^2 + b*x + c = 0

a = 2; b = 3; c = 5;

delta = b^2 – 4*a*c;

if delta > 0

x1 = (-b+sqrt(delta))/(2*a)

x2 = (-b-sqrt(delta))/(2*a)

elseif delta == 0

x1 = (-b+sqrt(delta))/(2*a)

else

real_a = -b/(2*a);

imag_b = sqrt(abs(delta)) / (2*a);

x1 = real_a – imag_b*i

x2 = real_a + imag_b*i

end

Introduction to MATLAB (Part 1)

2. Control Commands

When writing MATLAB M files, various control flow structures are often used. During the execution of these flow structures, it is often necessary to terminate loops early, exit subprograms, etc., which require control statements to achieve. Here, we mainly introduce commonly used continue and break statements.

The continue command is mainly used in loop statements to end the current operation of the loop body early, placing continue directly within the loop control body to work with if statements.

The break command, like the continue command, is also used in loop structures. When the break command is executed, the program exits the loop structure and moves to the next statement outside the loop.

The continue command jumps to the end statement of the loop, ending one iteration of the loop, while the break command exits the loop body where the break is located.

% Example of continue and break control statements

% Calculate the precision of floating-point number eps

EPS = 1;

for n = 1:1000

EPS = EPS / 2;

if (1 + EPS ) >1

continue

end

EPS = EPS * 2;

break;

end

EPS

Introduction to MATLAB (Part 1)

3. Concept of Program Vectorization

Vectorization is a special concept in MATLAB, referring to replacing loop structures with vectorized statements. Due to vectorization, data is pre-allocated memory, resulting in much faster execution speed.

Example of program vectorization

Calculating the square of each element in an array using both vectorization and loop structures.

% Loop structure

for i = 1:100

s1(i) = i^2;

end

% Vectorized processing

s2 = [1:100].^2;

% Loop structure

tic

num_max = 1000000;

for i = 1:num_max

s1(i) = i^2;

end

toc

% Vectorized processing

tic

s2 = [1:num_max].^2;

toc

4. Logical Arrays and Vectorization

In addition to basic numerical data types and strings, logical data is also a data type. Logical data can be created through relational and logical expressions or by using the logical command to create logical arrays.

Logical arrays play a very important role in the process of vectorization, allowing us to complete the vectorization process using logical arrays.

% Loop structure

tic

num_max = 1000000;

for i = 1:num_max

if i < 500000

s1(i) = i^2;

else

s1(i) = i;

end

end

toc

% Vectorized processing

tic

a = 1:num_max;

s2 = a(a<500000).^2;

toc

Introduction to MATLAB (Part 1)

Leave a Comment