MATLAB learning notes

Posted by crazychris on Mon, 28 Feb 2022 04:42:13 +0100

Primary directory

memorandum

  • Variable names begin with letters and number underscores
  • MATLAB is case sensitive
  • The WHO statement displays the names of all variables that have been used, and who is the specific information of the variables
  • format short has four digits after the decimal point (default), format long command displays 16 digits, format bank has two digits after the decimal point, and format rat is closest to the rational formula
  • Matrix representation: horizontal column semicolon
  • Functions in Matlab are saved in m file, the function name must be the same as the file name
  • When calculating multiplication, try to use Multiply instead of multiply, because the former can also be used when the input parameter is a matrix.
  • Matlab needs to use... To splice multiple lines

HELP

1.help
help  //Show help topic list
help plot //Display instructions about 3D drawing
help [ //Display help for special characters and symbols
help help //Display help information for help

2.lookfor
lookfor  //It can search a set of related commands through general keywords
lookfor fourier  //eg. find relevant instructions containing Fourier transform

3.demo  //When you open the help document, there will be many examples of functions and so on
4.helpwin  //ATLAB file help displayed in a window
5.helpdesk  //omprehensive hypertext documentation and troubleshooting.

Original link:[ https://blog.csdn.net/Gou_Hailong/article/details/106092705 ]

File path

1.Get current working path
cd

2.Change current working path,filepath For the working path to set
cd('filepath')
pathtool //Pop up the window of setting path

3.Returns the previous file path
cd('..\')

MATLAB function definition and expression

function [Output variable name] = Function name(Enter variable name)
Function handle  = @(Input variable) Output variable

MATLAB special variables and constants

NameMeaning
ansDefault variable name
epsFloating point relative error
i,jImaginary unit
InfInfinity
NaNIndefinite value (not a number)
piPI
realmaxMaximum positive real number
realminMinimum positive real number
narginNumber of actual input parameters of function
nargoutNumber of actual output parameters of function

MATLAB file reading and writing

commandeffect
save(filename,variables,'-ascii')Store the variable variables in a file as text
A= load(filename,'-ascii')Reading data from a text file
[num,txt,raw] = xlsread(filename,sheet,xlRange)Read Excel file
xlswrite(filename,A,sheet,xlRange)Infinity

array

This chapter is reprinted
Original link: https://blog.csdn.net/Gou_Hailong/article/details/109362945

Array creation

1.Simple creation
//Empty array - scalar - row / column vector - 2D / multidimensional array []
A=[];//Empty array
A=[1 2 3 4]; //Direct input method - line vector
A=[1;2;3;4]; //Direct input method column vector
A=start:step:end; //Colon method - line vector
A=linespace(start,end,n) //Arithmetic sequence
A=logspace(start,end,n)  //Proportional sequence 

2.Function creation
//If there is only one parameter in the following functions, a square matrix is generated
zeros(m,n)  //Generating a zero matrix of m x n
ones(m,n)   //Generate an m x n matrix with all elements of 1
eye(m,n)  //Generating the unit matrix of m x n
pascal(m,n)  //Generating Pascal matrix of m x n
hilb(n)  //Generating Hilbert matrix of n x n
rand(m,n)  //Generating m x n [0,1] uniformly distributed random number matrix
randn(m,n)  //Random number matrix generating normal distribution of m x n (0,1)
magic(n)  //Generate a magic square matrix of n x n, and the sum of elements on each row, column and diagonal is equal
diag(v,k)  //Diagonal array
/*The k diagonal element corresponds to the element of vector v, and k defaults to 0 
k>0 It indicates that the main diagonal deviates from the diagonal of k element positions to the right, 
k<0 Then deviate to the left and down
 If the input parameter v is a two-dimensional array, the function diag extracts diagonal elements to form a one-dimensional vector*/
diag([1 2],1)

3.Array properties
//1. Test the function, and the return value is 0(false) / 1(true) in logic
isempty,  isscalar,  isvector,  issparse
size(x)  //Returns the size of the array, a row vector that holds the dimension of the array
length(x) //Returns the larger dimension of the array
numel(x)  //Returns the number of all elements of the array
//Conversion between single subscript and full subscript: for array A with m rows and n columns,
A(x,y)=A((y-1)*m+x)
sub2ind(size(x),2,10)
[i j]=ind2sub(size(x),20)

Common operation

There are functions isequal(), all (a) to judge whether two matrices are equal( 😃 == B( 😃), Firstly, the following experiments were carried out:

//Logical 0(false) / 1(true)
isequal(1,1) //1
isequal(nan,nan) //0
isequal(inf,inf) //1

matlab judges whether two floating-point numbers are equal. In fact, it does not judge whether they are equal in the absolute sense, but there is a precision limit, which is expressed in code as follows:

a=[1:5];  // 1     2     3     4     5
b=[1:5];  // 1     2     3     4     5
all(a(:) == b(:));   //1
a(1,1)=1+1e-30;      //1     2     3     4     5
all(a(:) == b(:));   //1
abs(a-b)<eps         //Judging whether a and B are equal is equivalent to judging whether their absolute values are less than eps
//eps is a small number, which may be set by yourself.

Now we know that in matlab, nan~=nan, if you want to judge whether the two matrices (with nan elements in them) are equal, how to adjust them? A small function is provided here. The general idea is to replace nan with inf, and then judge whether the two matrices are equal.

%myequal.m
function eq=myequal(mat1,mat2)
mat1(isnan(mat1))=inf;  %This number can be anything else, as long as it's not nan that will do
mat2(isnan(mat2))=inf;
eq=isequal(mat1,mat2);
end

Common operation

1.Array connection
cat(dim,A1,A2,...)//Concatenates multiple arrays into large arrays in the specified direction
horzcat(A1,A2,...)//Horizontally connected array, equivalent to cat(2,A1,A2,...)
vertcat(A1,A2,...)//Vertically connected array, equivalent to cat(1,A1,A2,...)
repmat(A,m,n)   //Block copy function - treat array A as A single element and expand the extended array composed of m rows and n columns
blkdiag(A, B, ...)//Diagonal block generation function - Take arrays a and B as the main diagonal blocks of the new array, and fill other positions with zero blocks

2.Array flip
fliplr(A)//flip matrix in left/right direction
flipud(A)//upside down 
flipdim(A,k)//Flip in the specified direction, k=1 up and down, k=2 or so
rot90(A,k)//Rotate counterclockwise k*90 degrees
reshape(A,m,n)//Adjust the size of the array to m x n

3.Array operation
A+B
A-B
A*B
A/B // A*inv(B)
A\B // inv(A)*B
A^n // N is an integer and n A are multiplied
A.*B// Multiply the corresponding elements of two arrays
A./B// Each element of A is the numerator, and the corresponding element of B is the denominator. Divide one by one
A.\B// Each element of A is the denominator and the corresponding element of B is the numerator. Divide one by one
A.^B// Element by element exponentiation

4.Array lookup
a=find(A)//Return single subscript
[a,b]=find(A)//Return double subscript
//find function usually combines various relational operations and logical operations to realize various search functions

5.Array sorting
sort(A)

Common operation

m=yourmat;
[a,b]=size(m);             %The rows and columns of the matrix are a,b
num=a*b-numel(find(isnan(a))); %Except in the matrix nan Number of all elements outside
m1=reshape(m,a*b,1);      %Make it a column vector,Or directly m1=m(:);
max1=max(m1);             %Calculate maximum
min1=min(m1);             %Calculate minimum
mean1=nanmean(m1);        %Calculate Division nan Mean outside,mean
mode1=mode(m1);           %except nan Returns the mode with the smallest value
med1=nanmedian(m1);       %Ask for addition nan Median of,median
k(isinf(m1))=[];          %Remove inf
k(isnan(m1))=[];          %Remove nan
per=tabulate(k);          %Statistical frequency and frequency
find(m==1);               %find m The position of the element equal to 1 in the column vector
sum(sum(m>3));            %seek m Number of elements of matrix greater than 3
sum(sum(m==3));           %seek m Number of elements of matrix equal to 3
A=m(:);                   %Quickly turn a multidimensional matrix into a column vector
photo1(isnan(photo1))=inf;%Replace one number with another
photo1(photo1==1)=inf;
//Note: the above function for finding the maximum value is the operation of column vector. If it is used for matrix operation, the overlapping function can be used.

MATLAB drawing

plot function: change the color and line form of the center line of the image

Add features in the parentheses of the plot (x,y) function

legend function

Add image description

legend('A image','B image') 

hold on

Multiple functions appear in the same graph, followed by hole on

Topics: MATLAB