Matlab 基础操作

使用版本:Matlab 2016

一、基本运算

有点类似于 python,初始化不用设置数据类型;运算总体更偏向于数学

1、矩阵乘法

>> a=[1 2;1 2]

>> b=[3 4;5 6]

>> a*b
13 16				
13 16

上式就相当于:
[1212][3456]=[13161316] \begin{bmatrix} 1 & 2 \\ 1 & 2 \\ \end{bmatrix} * \begin{bmatrix} 3 & 4 \\ 5 & 6 \\ \end{bmatrix} = \begin{bmatrix} 13 & 16 \\ 13 & 16 \\ \end{bmatrix}

>> a.*b
3 8
5 12

但如果这样写就相当于 点对点间 的相乘

二、基本方法

1、清屏是 clc
2、输出方式 fprintf
3、whileif 后面的语句不用加括号,且都不用加 :

举例

x = 1;        //分号 可加可不加
if x+2==3
    fprintf('%.2f',x)   //记住用单引号
end           //必须加

4、elseif 要连着写
5、另一种输出方式是 disp(其便捷程度有点像 cout )

>> x = 2;
>> disp(x)
2
>> disp('132')
132

6、不等于符号 ~=
7、 a 模 b 就是 mod(a,b)
8、for 循环

for i = 1 : 5
	disp(i)
end

output: 1 2 3 4 5

for i = 1 : -1 : -5
	disp(i)
end

output: 1 0 -1 -2 -3 -4 -5

v = [0,1,2,3,4]
for i = v
	disp(i)
end

output: 0 1 2 3 4

9、求和函数(这个就类似 Excel)

v = [0,1,2,3,4]
sum(v)

output: 10

10、自定义函数(还是和 python 类似)
但区别就在于它每个函数都是独立一个文件(极致封装)

function mysum(n) //相当于 void
    s=0;
    for i = 1 : n
        s=i+s;
    end
    disp(s)
end

>> mysum(3)
6

function result = mysum(n)
    s=0;
    for i = 1 : n
        s=i+s;
    end
    result = s;
end

>> a = mysum(3)  //要是没有分号 程序则不会显示结果
6

三、基本画图

1、y = x

>> x = [1,2,3];
>> y = [1,2,3];
>> plot(x,y)

2、y = x2

>> x = -5 : 0.1 : 5;
>> y1 = x.^2;  //点对点
>> y2 = x.^2;
>> % axis equal  //将 x 与 y 座标变成一样长(不过这里注释掉了)
>> plot(x,y1,'green-o',x,y2,'black')  //绿色关键点标记 黑色为函数图像

3、可视图

>> y = [1.0,1.2,2.1,4.6,9.4,15.9];
>> bar(y)
>> x = 2000 : 2006;
>> bar(x,y)

4、3D Graph

>> theta = 0 : pi/50 : 6*pi;  // 6 pi是 360°
>> x = cos(theta);
>> y = sin(theta);
>> z = 0 : 300;
>> plot3(x,y,z)  //表示 3D

四、进阶画图

1、合并图像

x = -5 : 0.1 : 5;
y1 = x.^2;  
plot(x,y1,'black')  

hold on;  //合并图像

x = -5 : 0.1 : 5;
y2 = x.^3;
plot(x,y2,'green')  

grid on;  //添加网格  记住是最后加的
title('x^2 vs x^3');  //添加标题
xlabel('x-x');  // x轴添加描述
ylabel('y-y');  // y轴添加描述

2、分割图像

x = -4 : 0.1 : 4;

y1 = sin(x);
y2 = sin(2.*x);
y3 = sin(3.*x);
y4 = sin(4.*x);

// 不需要 hold on

subplot(2,2,1);  //图型分割为 2:2,选择第一层
plot(x,y1);
title('y = sin(x)');  //添加标题

subplot(2,2,2);
plot(x,y2);
title('y = sin(2.*x)');

subplot(2,2,3);
plot(x,y3);
title('y = sin(3.*x)');

subplot(2,2,4);
plot(x,y4);
title('y = sin(4.*x)');

3、分割独立图像

x = -4 : 0.1 : 4;

y1 = cos(x);
y2 = cos(2.*x);
y4 = cos(4.*x);

subplot(2,2,1);
plot(x,y1);
title('y = cos(x)');

subplot(2,2,2);
plot(x,y2);
title('y = cos(2.*x)');

subplot(2,2,[3,4]);  //将 3、4格按列表的形式组起来
plot(x,y4);
title('y = cos(4.*x)');

4、面图像

x = -3 : 0.1 : 3;
y = -3 : 0.1 : 3;
[X,Y] = meshgrid(x,y);  //形成一系列对应的点
Z = X.^2 + Y.^2;
surf(X,Y,Z)  //打印出面


x = -3 : 0.1 : 3;
y = -3 : 0.1 : 3;
[X,Y] = meshgrid(x,y);
Z = X.^2 + Y.^2;
plot3(X,Y,Z)  //打印出线
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章