[MatLab] Matrix operation and program structure

1. Matrix

        1. Definition

                The matrix is ​​included with [ ], the data is separated by a space, and the newline is represented by a ;.

A = [1 2 3 4 5 6]
B = 1:2:9            %1-9中的数,中间是步长(不能缺省)
C = repmat(B,3,2)    %将B横向重复2次,纵向重复2次
D = ones(2,4)        %生成2行4列的矩阵,且元素均为1

        2. Four operations of matrix

C = A+B     %对应相加
C = A-B     %对应相减
D = A*B'    %A乘B的转置
F = A .*B   %加点代表对应项相乘
G = A/B     %A除以B    等价与A*B的逆
H = A ./B   %A的对应项除B对应的项

        3. Matrix subscript operation

A = magic(5)
B = A(2,3)            %取2行3列位置的数
C = A(3,:)            %取3行的所有列    :一般表全部
[m.n] = find(A>20)    %找到A中>20的数并取出其索引值

2. Program logic & flow control

        1. Sequential structure

                Direct writing is a sequential structure.

        2. Loop structure

                ① for loop

for 循环遍历 = 初值:步长:终值
    执行语句 1;
end

                ② while loop

while 条件语句
    执行语句1;
end

        3. Choose structure

                ①if...end

if 条件表达式
    语句
end

                ②if...else..then

if 表达式
    语句体1
eles
    语句体2
end

                ③switch...case..end

switch 表达式(数值/字符串)
    case 数值/字符串1
        语句体1;
    case 数值/字符串2
        语句体2;
    ...
    otherwise
        语句体n
end

Guess you like

Origin blog.csdn.net/weixin_37878740/article/details/129282982