Get started quickly with MATLAB: scientific research, engineering, data analysis, MATLAB Introduction (Part 2) teaches you the basics! Share "MATLAB Beginners Tutorial MATLAB Programming - Getting Started with Novices (Clear Version)"

Bonus: There is information to share at the end of the article! !

1. "MATLAB Complete Study Manual (Video + Courseware + Code)"
2. "Introduction to MATLAB"
3. "Detailed Explanation of the Application of MATLAB in Scientific Computing"
4. "Case II Interaction between MATLAB and Excel"
5. "MATLAB Beginners Tutorial" MATLAB Programming - Getting Started with Novices (Clear Edition)"
6. "Matlab Commonly Used Functions Reference MATLAB Function Summary Proficient in MATLAB"
7. etc. . . .

foreword

Two days ago, we got acquainted with MATLAB briefly in ( Introduction to MATLAB (Part 1) ), and learned the basics of MATLAB. Today, we will continue to introduce you from two aspects of file reading and MATLAB drawing.

1. File reading

1. Workspace data reading

In MATLAB, the variable of the workspace can be saved as a file, and the data imported from the file can be saved as a variable. The common command is the save function.

save: Save all variables in the current workspace to the file matlab.mat in binary format, save different types of data according to the corresponding maximum precision, and save the corresponding variable names.

save('filename'): Save the file to the current directory, the file name is filename.mat, if you need to save it to another directory, you need to add the file path.

save('filename','var1','var2'): Save the specified variables in the workspace to the file filename.mat.

load: Load all variables in matlab.mat, if the file does not exist, an error will be returned.

load filename: load all the variables in the specified file filename, and determine the file read-in method according to the file suffix when loading.

picture

insert image description here

2. Text file reading

A = fread(fid): Read a file in binary format through the file pointer. The read data is stored in the array A. During the process of reading data, the file pointer can be detected by feof from the beginning to the end.

A = fread(fid,count): read count array elements, after fread reads in, the file pointer is positioned at the next byte of the read byte, and the subsequent read bytes start from here.

A = fread(fid,count,precision,skip): read data with the precision specified by precision, and skip can choose to skip several characters.

insert image description here

insert image description here

3. Commonly used data import and export functions

dlmread: read data from a delimited text file

dlmwrite: write data to a delimited text file

textread: read formatted text from a file

textscan: After opening the file with the fopen function, read the formatted file

xlsread: read data in a spreadsheet

imread: read data from image file

imwrite: write data to an image file

aviread: read data from avi file

4. Import and output of image files

Image file reading can be realized through the imread function, which only supports image files in multiple formats, including BMP, CUP, GIF, HDF, ICO, JPG, PBM, PCX, PGM, PNG, PNM, PPM, RAS, TIF , XWD.

A = imread(filename,fmt): read the image file from filename, if the image file is not in the current directory, you need to point out the path, fmt is the image file format

[X,map] = imread(filename,fmt): read the bitmap file into X, read the related color data into the map, and the color data changes between [0,1].

[~] = imread(URL,filename): Import pictures from the network, url is the URL

insert image description here

insert image description here

picture

Image file output can be realized through the imwrite function, and the supported image file formats include BMP, CUP, GIF, HDF, ICO, JPG, PBM, PCX, PGM, PNG, PNM, PPM, RAS, TIF, and XWD.

imwrite(A,filename,fmt): Write the image A into the filename file in the specified image format fmt. A can be a gray image of m n or a color image of m n*3.

imwrite(X,map,filename,fmt): Write the bitmap and related colormap in X to the file in the specified format fmt.

% draw the image

x = 0:pi/12:2*pi;

plot(sin(x),cos(x),'color','blue','linewidth',5,'marker','d');

axis square

PS.Color = [0.7,0.7,0];

PS.LineWidth = 2;

line(sin(7*x),cos(7*x),PS)

[X,map] = imread('figure','jpg');

imshow(X,map)

imwrite(X,'figure_new','jpg')

insert image description here

Two, MATLAB drawing

1. Two-dimensional graphics drawing

The plot function is a commonly used function for drawing two-dimensional graphics in Matlab. This function draws the data points in the array on the coordinate plane, and connects these points through straight lines to form a continuous curve. The main command format is as follows:

1、plot(x,‘PropertyName’,PropertyValue)

x represents the data for drawing the chart, Property represents the character option of the attribute, and PropertyValue represents the corresponding selected value.

When x is a one-dimensional array, draw the curve with the subscript of the array element as the abscissa and the value of the element as the ordinate;

When x is a two-dimensional array, each column of the array is the total coordinate, and the subscript of the array is the abscissa to draw multiple curves.

2、plot(x,y,‘PropertyName’,PropertyValue)

When x and y are arrays of the same dimension, draw a curve with x and y as horizontal and vertical coordinates respectively,

When x is a one-dimensional array and y is a matrix, one dimension of y is equal to the dimension of x, and multiple curves are drawn;

When both x and y are matrices, take the corresponding x and y as the horizontal and vertical coordinates respectively, and the number of curves is equal to the number of matrix columns.

3、plot(x1,y1,x2,y2,‘PropertyName’,PropertyValue)

Simultaneously draw curves with x1 and y1, x2 and y2 as horizontal and vertical coordinates in the window.

%plot函数绘图示例

%生成一维数组及参数数组

a = 0:0.1:1;

t = 0:0.01:1;

%生成二维数组

y = sin(3*t').*exp(-t')*a;

%figure1:二维数组绘制曲线

subplot(2,2,1)

plot(y)

axis([0,100,0,1]);

xlabel('index');ylabel('y');

title('figure1');

%figure2: One-dimensional array and two-dimensional array draw curve

subplot(2,2,2)

plot(t,y)

axis([0,1,0,1]);

xlabel('t');ylabel('y');

title('figure2');

%figure3:二维数组和一维数组绘制曲线

subplot(2,2,3)

plot(y,t)

axis([0,1,0,1]);

insert image description here z

  1. Linetypes, markers and colors

Common line types, markers, and colors in MATLAB are shown in the figure below.

insert image description here

%plot函数参数示例

%生成一维数组

t = 0:pi/20:3*pi;

%生成因变量数组

y = exp(-t/3).*sin(2*t+3);

y1 = exp(-t/3);

%绘制曲线

plot(t,y,'b:*',t,y1,'r-')

xlabel('t');ylabel('y');

title('Linestyle and markers');

legend('y=exp(-t/3).*sin(2*t+3)','y1=exp(-t/3)');

insert image description here

3. 3D curve drawing

The plot3 function is a common function for Matlab to draw three-dimensional curves. When inputting parameters, you need to input the third parameter array.

plot(x,y,z,LineSpec,‘PropertyName’,PropertyValue)

If x, y, and z are arrays of the same dimension (vector, matrix), the corresponding columns are used as x, y, and z coordinates, and the number of curves is equal to the column dimension of the matrix.

%plot3函数绘图示例

t = 0:pi/50:10*pi;

plot3(sin(t),cos(t),t,'r*-');

xlabel('sin(t)');ylabel('cos(t)');zlabel('t');

title('figure1:helix');

%绘制多条曲线

figure;

x = linspace(0,3*pi,200);

z1 = sin(x); z2 = sin(2*x); z3 = sin(3*x);

y1 = zeros(size(x)); y2 = ones(size(x));

y3 = 2*ones(size(x));

plot3(x,y1,z1,'r*',x,y2,z2,'bp',x,y3,z3,'mx');

xlabel('x');ylabel('y');zlabel('z');

title('figure2:sin(x),sin(2x),sin(3x)');

insert image description here

4. Mesh and surface plotting

The three-dimensional grid map is equivalent to defining a grid surface with the z coordinates on the xy plane. Adjacent points are connected by straight lines. The grid nodes are the data points of z, which is realized by the mesh function in Matlab.

mesh(z): Draw a grid graph with the subscripts of the columns and rows of the z matrix as the independent variables of the x and y axes;

mesh(x,y,z): x and y are independent variable matrices, z is a function matrix based on x and y;

Compared with the mesh function, the surf function fills all the grids on the surface with color, and the command format is similar to the mesh function. However, flat shadows and interpolated shadows are provided.

%mesh function drawing example

x = 0:pi/20:2*pi;

y = 0:pi/20:2*pi;

[X,Y] = meshgrid(x,y);

Z = sin(X)+cos(Y);

mesh(X,Y,Z)

xlabel('X');ylabel('Y');zlabel('Z');

title('figure1');

figure;

mesh(Z)

xlabel('X');ylabel('Y');zlabel('Z');

title('figure2');

insert image description here

%surf function drawing example

x = 0:pi/20:2*pi; y = 0:pi/20:2*pi;

[X,Y] = meshgrid(x,y);

Z = sin(X)+cos(Y);

surf(X,Y,Z)

shading flat

xlabel('X');ylabel('Y');zlabel('Z');

title('figure1');

figure;

surf(Z)

shading interp

xlabel('X');ylabel('Y');zlabel('Z');

title('figure2');

insert image description here

  1. Contour drawing

The contour map can connect points with the same value to draw a curve or surface of equal value. The command format of the commonly used MATLAB function for drawing a contour map is:

contour(z): Draw the contour map expressed by z

coutour(z,n): The parameter n is the number of contour maps to be drawn

contour(z,v): vector v defines the number and value of contour lines

% contour plot example

x = 0:pi/20:2*pi;

y = 0:pi/20:2*pi;

[X,Y] = meshgrid(x,y);

Z = sin(X)+cos(Y);

surf(X,Y,Z)

shading interp;

contour(X,Y,Z,-2:0.4:2)

xlabel('X');ylabel('Y');

title('二维等值线图');

figure

contour3(X,Y,Z,60)

xlabel('X');ylabel('Y');zlabel('Z');

title('三维等值线图');

insert image description here

  1. Colors represent contour lines

%Color represents contour plot example

x = 0:pi/20:2*pi;

y = 0:pi/20:2*pi;

[X,Y] = meshgrid(x,y);

Z = sin(X)+cos(Y);

surf(X,Y,Z)

shading interp;

figure

contourf(X,Y,Z,20)

insert image description here

7. Special graphic drawing

(1) Pie chart drawing

pie(x): Draw a pie chart of vector x, each element in x is each sector in the pie chart.

pie(x,explode): The parameters explode and x are arrays of the same dimension. If there are non-zero elements in the explode, the corresponding elements in the x array will be moved outward in the pie chart to highlight the value of the element.

pie(~, labels): The parameter labels represent the sector on the pie chart.

%饼图绘制示例

%向量参数设定

x = [1,3,0.5,2.5,2];

explode = [1,0,0,0,0];

subplot(1,2,1)

pie(x,explode,{
    
    'a','b','c','d','e'});

title('二维饼图')

subplot(1,2,2)

pie3(x,explode);

title('三维饼图')

insert image description here

(2) Histogram and ladder diagram

bar(y): Draws a bar for each element of the one-dimensional array y.

bar(x,y): Draw a histogram y on the abscissa vector x, and the x vector needs to be arranged in an increasing manner.

bar(~,width): width is used to set the relative width of the histogram bars and the spacing between the bars.

hist(y,n): Indicates the distribution of values ​​in the array y, n indicates the number of columns in the histogram, and the default is 10.

%绘制直方图和柱形图

x = -3:0.3:3;

y = exp(-x.^2);

bar(x,y,0.8);

xlabel('x');ylabel('y')

figure

bar3(x,y,0.9)

xlabel('x');ylabel('y')

y = randn(1,10000);

figure

hist(y,30)

insert image description here

Summarize

MATLAB is a widely used scientific computing tool, suitable for scientific research, engineering, data analysis and other fields. To know MATLAB, you need to understand its overview and characteristics, and learn to use the command window, create M files, directory and file management, search path management and other basic operations. Basic knowledge of MATLAB includes simple calculations, basic operation symbols, values, variables and expressions, generation and search of arrays. Programming fundamentals include flow control, control commands, logical arrays, and vectorization. Mastering these basic knowledge can make using MATLAB more handy.
insert image description here
Pay attention to the WeChat public account: Recharge your resources
Reply: MATLAB
insert image description here

1. "MATLAB Complete Study Manual (Video + Courseware + Code)"
2. "Introduction to MATLAB"
3. "Detailed Explanation of the Application of MATLAB in Scientific Computing"
4. "Case II Interaction between MATLAB and Excel"
5. "MATLAB Beginners Tutorial" MATLAB Programming - Getting Started with Novices (Clear Edition)"
6. "Matlab Common Functions Reference MATLAB Function Summary Proficient in MATLAB"
7. Research, postgraduate entrance examination, IT, source code, etc. . . . Massive resources are free to share

Guess you like

Origin blog.csdn.net/CDB3399/article/details/130826008
Recommended