Fundamentals of MATLAB programming

Catalogue of series articles

Are there any students who have not learned the language matlab like me, but want to learn the course of intelligent optimization algorithm and matlab examples.

Article catalog

  • Basic understanding
  • Relation and logical operation
  • Data input and output
  • Select and loop statements
  • Function file
  •   Matlab drawing


The following is my summary of some basic matlab programming, I hope it can be helpful to you.

1, Basic understanding

(1) M file

m files have a. m extension.

M files can be divided into two types according to different calling methods:

  Script: script file / command file  

Function: function file

(2) Establishment and opening of M file

Create a new M file

Menu operation (File, New, File)  

Command operation (edit M file name)

  Command button (shortcut key)

Open an existing M file

Menu operation   ( File ,Open )  

Command operation (edit M file name)  

Command button   (shortcut key)  

Double click the M file

M file control flow

2, Relation and logical operation

1. Relational operators

< (less than)   > (greater than) = = (equal to)   <= (less than or equal to)    >= (greater than or equal to)   ~= (not equal to)

The relational operator can be used to compare two arrays of the same size, or to compare an array with a scalar. In the latter case, the scalar is compared with each element in the array, and the comparison result is the same as the size of the array.

2. Logical operators

&(and  )   | (or)   ~ (non)    xor(x,y) (XOR)

3, Data input and output

(1) Data input

A = input (prompt)

The prompt message is A string,   This command requires the user to enter the value of A (which can be A number or A string)

eg.   A=input('Please input A: ')

If it is an input string, you can also use the following method

A = input (prompt message,'s')

Note: do not add single quotation marks to the input string at this time!

eg.  name=input('What''s your name? ', 's')

A=input('Please input A: ')
name=input('What''s your name? ', 's')


Please input A: 4

A =


What's your name? qingyun

name =


(2) Output of data: disp


The value of the output variable X can be a numeric matrix or a string

name=input('What''s your name? ', 's')

What's your name? qingyun

name =


A='Hello,everyone !';


>> jichu
Hello,everyone !

4, Select and loop statements

(1) if conditional statement

Single branch structure

if expression ((condition)    

statements (Statement group)

for i=1:100


Double branch structure

if expression ((condition)    

statements1(Statement group 1)


statements2(Statement group 2)

x=input('Please input x: ')


Please input x: 3

x =



Multi branch structure

if expression1 (Condition 1)
   statements1(Statement group 1)
elseif expression2 (Condition 2)
   statements2(Statement group 2)
 ... ... 
elseif expressionm (condition m)
   statementsm(Statement group m)
   statements(Statement group)
x=input('Please input x: ')
     disp('I need to think about it')

Please input x: 3

x =


I need to think about it

(2) Cyclic structure

for loop

for variable=expression
    statement(Circulation body)
x = 0;
for i = 1:100
    x = x + i;

>> jichu
s = 0;
for i = 1:2:100  %%%2 Is the step size
    s = s + i;


>> jichu

while loop

while expression ((condition)
    statement(Circulation body)
s = 0;
k = 0;
while(k <= 100)
    s = s + k;
    k = k + 1;

>> jichu

Other flow control statements

break and continue

The break statement is used to terminate the execution of the loop, that is, to jump out of the innermost loop   The continue statement is used to end this cycle and proceed to the next cycle   Break and continue are generally used with if statements


The return statement is used to exit a running script or function. It is usually used in the function file.

switch statement

Execute different statements according to different values of the expression.

switch expression ((expression)
   case value1 (Expression 1)
        statement1(Statement group 1)
   case value2 (Expression 2)
        statement2(Statement group 2)
      ... ...
   case valuem (expression m)
        statementm(Statement group m)
        statement (Statement group)
max(A,[],2)Find the maximum value of each row in the matrix
min(A,[],2)Find the minimum value of each row in the matrix
max(A,[],1)Find the maximum value of each column in the matrix
min(A,[],1)Find the minimum value of each column in the matrix

5, Function file

The function file is guided by a function statement

function [out1,out2,...] = function name (in1,in2,...)

%Note description section (optional)

Function body statement (required)

The first line is the leading line, indicating that the M file is a function file   The naming rules of function names are the same as variable names (must start with letters)   When there is more than one output line parameter, enclose it in square brackets

General format for function calls

Output argument list = function name (input argument list)


function avg = fun(x) % Main function

n = length(x);

avg = mean(x, n);

function a = mean(x, n) % Subfunction

a = sum(x)/n;

Six,   Matlab drawing

Commonly used

x = 0:pi/100:2*pi;  %%%0 To 2 pi,In the middle pi/100 Take points for spacing x Take 0 respectively, pi/100,2pi/100,3pi/100.......2*pi
y = sin(x);
title('Qingyun Pavilion')
xlabel('propitious clouds bringing well-being to all')
ylabel('Qingyun studio')


  basic form


x. If y is a vector, take the element in X as the abscissa and the element in y as the ordinate to make a plane curve. At this time, X and y must have the same length.

x. If y is a matrix, the columns of X and the corresponding columns in y are combined to draw multiple plane curves. At this time, X and y must have the same size.

x is a vector and Y is a matrix. If the length of x is equal to the number of rows of Y, the columns in x and y are corresponding to draw multiple plane curves; otherwise, if the length of x is equal to the number of columns of Y, the rows in x and y are corresponding to draw multiple plane curves. At this time, the length of x must be equal to the number of rows or columns of Y.

Properties of the drawing

Basic properties of points and lines


Where string is a string enclosed in single quotation marks, which is used to specify the attributes of the graph (the shape and color of points and lines)

>> x=[0:0.2:2*pi];
>> plot(x,cos(x));
>> plot(x,cos(x),'r+:');
>> plot(x,cos(x),'bd-.');
>> plot(x,cos(x),'k*-');

Draw multiple function images at the same time

plot(x1,y1,s1,x2,y2,s2, ... ,xn,yn,sn)

Equivalent to:

hold on

Basic properties of graphics

            b     blue   Blue      .     point              -     solid
            g     green   Green       o     circle             :     dotted
            r     red     Red       x     x-mark             -.     dashdot  
            c     cyan   Green      +     plus               --     dashed   
            m     Magenta magenta   *     star             (none)   no line
            y     Yellow yellow       s     square
            k     black   Black       d     diamond
            w     white   White       v     triangle (down)
                               ^     triangle (up)
                               <     triangle (left)
                               >     triangle (right)
                                p     pentagram Pentagram
                                h     hexagram   Hexagonal star

Additional properties of the drawing



Axis dimension

xlabel('text ') or   ylabel(’text’)

Add legend

legend(string1,string2, ...)

Other related commands

show grid

grid on or grid off

Keep the image of the current window

hold on or hold off

New drawing window



Qingyun Pavilion, come on!!!

Tags: MATLAB Machine Learning

Posted on Fri, 03 Dec 2021 19:57:54 -0500 by mihomes