自学内容网 自学内容网

MATLAB Learning Roadmap (1)

MATLAB is designed to work with matrices and arrays efficiently. 


1 Fundamentals and Basics

(1)command window

1. Type a command

After typing a command, press Enter to execute it. MATLAB will process the command and display the result (if any) in the Command Window.

2. see the result

In the diagram, you see I've typed the command 2+3. The result, ans = 5, appears on the next line.

  • ans is a special variable that MATLAB uses to store the most recent result if you don't assign the result to a specific variable.

Sometimes, commands don't produce a direct output to display. For example, if you create a variable:

myVariable = 15;

You won't see an immediate result printed. However, the variable is now stored in the Workspace.

3. create variables

  • Variable names must start with a letter.
  • They can contain letters, numbers, and underscores.
  • MATLAB is case-sensitive, so 'myVariable' and 'myvariable' are different.
  • Choose meaningful names that describe what the variable holds.

MATLAB is dynamically typed, meaning you don't have to explicitly declare the data type of a variable. MATLAB figures it out based on the value you assign.

Structure

 Arrays of structures are incredibly useful in MATLAB. Imagine you have information about multiple books, each with its title, author, and year. Instead of creating separate structures for each book, you can efficiently store them all within a single array.

% Create the first student structure
student1.name = 'Alice';
student1.age = 18;
student1.grade = 90;

% Create the second student structure
student2.name = 'Bob';
student2.age = 17;
student2.grade = 85;

% Create the third student structure
student3.name = 'Charlie';
student3.age = 19;
student3.grade = 95;

% Create an array of structures
students = [student1, student2, student3];

% Access and print information for a specific student
disp(['Name of the second student: ', students(2).name]);
disp(['Grade of the second student: ', num2str(students(2).grade)]);

% Loop through the array and print name and grade for each student
for i = 1:length(students)
    disp(['Student ', num2str(i), ':']);
    disp(['   Name: ', students(i).name]);
    disp(['   Grade: ', num2str(students(i).grade)]);
end
Cell Arrays

 Cell arrays are a powerful data type in MATLAB that offer great flexibility. They are similar to regular arrays, but with one key difference: each cell within a cell array can hold data of any type. So you can mix numbers, text, matrices, even other cell arrays, all in one structure.

Creating a cell array in MATLAB is simple. You use curly braces {} to define the contents of each cell. For example:

  1. We create a cell array called 'myCellArray' containing various data types.
  2. We use curly braces {} to access the contents of a specific cell.
  3. We use parentheses () to access elements within the content of a cell.
  4. We modify the contents of a cell by assigning a new value to it.
  5. We add a new cell to the end of the array.
  6. The celldisp function displays the entire cell array in a readable format.
% Create a cell array
myCellArray = {'Hello', 25, [1 2; 3 4], true};

% Access elements using curly braces {}
 disp(myCellArray{1});   % Output: Hello
disp(myCellArray{3});   % Output: [1 2; 3 4]

% Access content within a cell using parentheses ()
disp(myCellArray{3}(2,1)); % Output: 3 (element in row 2, column 1 of the matrix)

% Modify the contents of a cell
myCellArray{2} = 'World!'; 
disp(myCellArray{2});   % Output: World!

% Add a new cell to the end of the array
myCellArray{end+1} = {10, 20, 30}; 
disp(myCellArray{end}); % Output: {10 20 30} (a nested cell array)

% Display the entire cell array
celldisp(myCellArray)
Function Handles

 Function handles are a powerful feature in MATLAB that allow you to treat functions like any other variable. Think of them as pointers or references to functions.

To create a function handle, you use the @ symbol before the function name. Here's an example:

% Create a function handle for the 'sin' function
handleToSin = @sin; 

% Call the sin function through the handle:
result = handleToSin(pi/2); % Calculates sin(pi/2)

disp(result) % Output: 1

This code demonstrates some key concepts:

  1. Defining Separate Area Functions: We define separate functions for calculating the area of a circle and a rectangle.
  2. Creating a Cell Array of Function Handles: We create a cell array 'areaFunctions' that stores handles to our area calculation functions.
  3. User Input: The code gets the user's choice of shape and the necessary dimensions.
  4. Conditional Function Calls: An if-elseif-else structure uses the user's input to decide which function handle to call from the 'areaFunctions' array.
% Define functions for calculating areas
function area = calculateCircleArea(radius)
    area = pi * radius^2;
end

function area = calculateRectangleArea(length, width)
    area = length * width;
end

% Create a cell array of function handles
areaFunctions = {@calculateCircleArea, @calculateRectangleArea};

% Get user input for shape and dimensions
shape = input('Enter shape (circle or rectangle): ', 's');

% Calculate area based on the selected shape
if strcmp(shape, 'circle')
    radius = input('Enter radius: ');
    area = areaFunctions{1}(radius); % Call circle area function
elseif strcmp(shape, 'rectangle')
    length = input('Enter length: ');
    width = input('Enter width: ');
    area = areaFunctions{2}(length, width); % Call rectangle area function
else
    error('Invalid shape entered.');
end

% Display the result
disp(['Area of the ', shape, ': ', num2str(area)]);

4. use variables in calculations

Key Points:

  • Variables store the results: The output of these matrix operations (e.g., LUPxVD) is assigned to variables. You can then use these variables for further calculations or analysis.
  • Built-in functions: MATLAB provides powerful built-in functions like lu()\ (for solving linear systems), and eig() to perform these operations.
  • Efficient computation: These functions are optimized for numerical computations, making them much faster than writing your own algorithms.

Here's a breakdown of how to use variables with matrices and vectors:

% Create a matrix and a vector
A = [1 2 3; 4 5 6]; % A 2x3 matrix
v = [7 8 9];        % A row vector

% Perform matrix multiplication
result = A * v';    % Multiply matrix A by the transpose of vector v

% Access elements using variables
row = 2;            % Define a variable for the row index
column = 1;         % Define a variable for the column index
element = A(row, column); % Access the element at the specified row and column

disp(result)       % Display the result of the matrix multiplication
disp(element)      % Display the selected element

In this code:

  1. A = [1 2 3; 4 5 6]; and v = [7 8 9];: These lines create a matrix A and a vector v, respectively.
  2. result = A * v';: This line performs matrix multiplication. Notice the use of the apostrophe (') to transpose vector v, making it compatible for multiplication with matrix A.
  3. row = 2; and column = 1;: These lines define variables to store row and column indices.
  4. element = A(row, column);: This line accesses a specific element of the matrix using the variables row and column.
  5. disp(result); and disp(element);: These lines display the results.

In matrix multiplication, the inner dimensions must match. For example, to multiply a 2x3 matrix by a vector, the vector must have 3 elements (or be transposed to become a 3x1 vector).

 Here are some examples of how variables can be used for those more advanced matrix operations:

% Matrix Decomposition (LU Decomposition)
A = [2 1 1; 4 3 3; 8 7 9];
[L, U, P] = lu(A);  % LU decomposition with pivoting

% Solving Linear Systems (Ax = b)
A = [1 2; 3 4];
b = [5; 11];
x = A\b;          % Solve for x

% Eigenvalue Calculations
A = [3 1; 0 2];
[V, D] = eig(A);   % Calculate eigenvectors (V) and eigenvalues (D)
LU Decomposition

LU Decomposition is a powerful technique in linear algebra that breaks down (or decomposes) a matrix into two simpler matrices: a lower triangular matrix (L) and an upper triangular matrix (U). This decomposition can then be used to solve linear systems of equations more efficiently and for other matrix operations.

LU Decomposition is widely used in applications like:

  • Solving systems of linear equations: It's much faster to solve systems after decomposition than using general methods like Gaussian elimination for large systems.

  • Calculating determinants: The determinant of a matrix is easily found as the product of the diagonal elements of U.

  • Finding the inverse of a matrix: LU decomposition simplifies the process of inverting a matrix.

    Overall, it makes computationally intensive matrix operations more efficient, especially for larger matrices.

You can perform LU decomposition in MATLAB using the lu() function:

[L, U, P] = lu(A); 
  • A is the matrix you want to decompose.
  • L is the resulting lower triangular matrix.
  • U is the resulting upper triangular matrix.
  • P (optional) is the permutation matrix if pivoting is used.
Solving Linear Systems

These systems involve multiple linear equations with the same variables, and the goal is to find the values of those variables that satisfy all the equations simultaneously.

The diagram shows how a system of linear equations can be compactly represented using matrices and vectors.

  • The coefficients of the variables form the coefficient matrix (A).
  • The variables themselves are represented as a vector (x).
  • The constants on the right-hand side of the equations make up the constant vector (b).

This allows us to write the system in a concise form: Ax = b

MATLAB's Powerhouse: The Backslash Operator (\)

MATLAB provides a remarkably simple yet powerful way to solve linear systems: the backslash operator (\).

A = [2 1; 1 -1];   % Coefficient matrix
b = [5; 0];       % Constant vector
x = A\b;          % Solve for x
disp(x)            % Display the solution vector x

In this code:

  1. We define the coefficient matrix A and the constant vector b.
  2. x = A\b; does the magic! This single line uses the backslash operator to solve the system and store the solution in the vector x.
  3. disp(x); displays the solution vector.
Eigenvalue Calculations

Imagine you have a matrix A that represents some kind of transformation (like stretching, rotating, or reflecting) in a vector space. An eigenvector (v) of A is a special vector that, when transformed by A, only changes its scale (length) but not its direction. The corresponding eigenvalue (λ) represents the factor by which the eigenvector is scaled.

The Equation

This relationship is captured by the eigenvalue equation:

A * v = λ * v

where:

  • A is the square matrix.
  • v is the eigenvector (a non-zero vector).
  • λ is the eigenvalue (a scalar).

Finding Eigenvalues and Eigenvectors in MATLAB

MATLAB makes it easy with the eig() function:

A = [3 2; 1 4];  % Define the matrix
[V, D] = eig(A); % Calculate eigenvectors and eigenvalues

disp(V)          % Display the matrix of eigenvectors
disp(D)          % Display the diagonal matrix of eigenvalues

In this code:

  1. A = [3 2; 1 4]; defines the matrix.
  2. [V, D] = eig(A); calculates the eigenvectors and eigenvalues.
    • V is a matrix where each column represents an eigenvector.
    • D is a diagonal matrix where the diagonal entries are the eigenvalues.
  3. disp(V) and disp(D) display the results.

5. explore bulit-in functions

①Mathematical  Functions

  • Non-negative numbers include zero and all positive numbers.
x = 9; 
real_root = realsqrt(x);  % Calculates the real square root of 9
disp(real_root)          % Output: 3

y = -4; 
% real_root = realsqrt(y); % This would throw an error because y is negative

The nthroot() function in MATLAB calculates the real nth root of real numbers. Think of it as a generalization of the square root function (sqrt()). Instead of always finding the 2nd root, nthroot() lets you find any root!

You provide two inputs to the nthroot() function:

  1. x: The number for which you want to find the root.
  2. n: The degree of the root (e.g., 2 for square root, 3 for cube root, etc.).
% Cube root of 27
x = 27;
n = 3;
result = nthroot(x, n); 
disp(result)  % Output: 3

% Fifth root of -32
x = -32;
n = 5;
result = nthroot(x, n); 
disp(result)  % Output: -2

The function then returns the real number r such that r^n = x.

The special case: 0! is defined to be 1.

In MATLAB:

You can calculate factorials using the factorial() function:

n = 6;
fact_n = factorial(n);
disp(fact_n)  % Output: 720 
②Matrix and Array Operations

ⅠAddition / Subtraction Multiplication

For Arrays:

Addition and subtraction are performed element-wise. This means you add or subtract the corresponding elements of the arrays. The arrays must have the same dimensions for this to work.

A = [1 2 3; 4 5 6];
B = [2 4 6; 8 10 12];

Here's how you'd perform element-wise operations:

% Element-wise Multiplication
C = A .* B;  % Result: C = [2 8 18; 32 50 72]

% Element-wise Division
D = A ./ B;  % Result: D = [0.5 0.5 0.5; 0.5 0.5 0.5]

% Element-wise Power
E = A .^ 2; % Result: E = [1 4 9; 16 25 36]

 For Matrices:

It's the same idea as with arrays, but we're thinking in terms of linear algebra. You add or subtract the corresponding elements, and the matrices must have the same dimensions.

The dimensions must be compatible for matrix multiplication to be defined. The number of columns in the first matrix must match the number of rows in the second matrix. 

Ⅱ Division

Matrix division in MATLAB is a bit more nuanced than multiplication. It involves finding the matrix inverse and is closely tied to solving systems of linear equations. 

  • Invertibility: Not all matrices have an inverse. A matrix is invertible (or non-singular) only if its determinant is non-zero.
  • Order Matters: Like matrix multiplication, the order of division is crucial. A \ B is not the same as B / A.
  • Array Division: For element-wise division of arrays, use the ./ operator.

Left division (using the backslash operator \) is a powerful tool for solving linear equations in MATLAB. 

The Equation:

Left division is used when you want to solve a matrix equation of the form: xA = B, where:

  • A is a known matrix (often a coefficient matrix).
  • B is a known matrix or vector (often representing constants).
  • x is the unknown matrix or vector you want to find.

How it works:

MATLAB's \ operator essentially does the following:

  1. Finds the inverse of matrix A: It calculates inv(A).
  2. Multiplies the inverse by B: It performs inv(A) * B to get the solution x.

Example:

Let's say you have the system of equations:

2x + 3y = 8 4*x - y = 2

You can represent this in matrix form as AX = B:

[2 3] * [x] = [8] [4 -1] [y] [2]

A = [2 3; 4 -1];
B = [8; 2];

X = A \ B; 
disp(X) % Output: [1; 2]

This code solves for the vector X, which contains the values of x and y. The result X = [1; 2] means x = 1 and y = 2.

 The Equation:

Right division is used to solve equations of the form AX = B, where:

  • A is a known matrix.
  • B is a known matrix or vector.
  • x is the unknown matrix or vector we want to solve for.

How it works:

The / operator in MATLAB performs these steps:

  1. Finds the inverse of matrix A: Calculates inv(A).
  2. Multiplies B by the inverse: Performs B * inv(A) to get the solution x.

Example:

Let's use the same system of equations as before:

2*x + 3*y = 8
4*x - y = 2

In matrix form (AX = B):

[2  3] * [x] = [8]
[4 -1]   [y]   [2]
A = [2 3; 4 -1];
B = [8; 2];

X = B / A;
disp(X) % Output: [1; 2]

 Ⅲ Transpose

The transpose is a fundamental operation that flips a matrix or array over its diagonal, swapping rows and columns.

How it Works:

  • Notation: The transpose of a matrix A is denoted by A' (A with an apostrophe).
  • Process: The element at row i and column j in the original matrix becomes the element at row j and column i in the transposed matrix.
A = [1 2 3;
     4 5 6];

B = A'; 

disp(B) % Output: [1 4;
                   2 5;
                   3 6]

In this example, the 2x3 matrix A becomes a 3x2 matrix B after transposing. Notice how the rows of A have become the columns of B.

Ⅳ Power

1. Element-wise Power:

A = [1 2 3; 4 5 6];
B = A .^ 2;  % Square each element

disp(B) % Output: [ 1  4  9;
               16 25 36] 

2. Matrix Power:

A = [2 1; 1 2];
C = A ^ 3;  % A * A * A

disp(C)  % Output: [13  12; 
               12  13] 

Reference

Desktop Basics - MATLAB & Simulink

WhatAreAllTheseWindows

LU decomposition - An Example Calculation - YouTube

How to Solve a System of Linear Equations

#008 Linear Algebra - Eigenvectors and Eigenvalues

How to Use MATLAB's built-in functions - YouTube


原文地址:https://blog.csdn.net/2302_77608969/article/details/143483220

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!