Matlab基础语法

942 阅读8分钟

tab键自动补全

本文已参与「新人创作礼」活动,一起开启掘金创作之路

zeros(m)     %创建 m x m 的全零矩阵  

zeros(m,n)   %创建 m x n 的全零矩阵  

ones(m)      %创建 m x m 的全1矩阵  

ones(m,n)    %创建 m x n 的全零矩阵  

diag(A)      %提取矩阵 A 的对角元素      

fliplr(A)    %对矩阵进行 左右 对称翻转 

flipud(A)    %对矩阵进行 上下 对称翻转 

magic(m)     %创建 m x m 的魔方矩阵  (暂无实际用途)
clear      % 清除变量
clc        % 清空控制台
clf        % 清除图形
close      % 关闭活动窗口
close all  % 关闭所有活动窗口

type sphere % 查看函数文件代码 or type('sphere')
 
pathtool 		% 打开设置路径窗口

dsip(x)     % 显示函数 相当于打印

fprintf     % 格式化输出
sprintf			% 格式化输出,结果可以赋值给变量

绘图

x=[0:2:18];  %步长为2
y=[0,0.33,4.13,6.29,6.85,11.19,13.19,13.96,16.33,18.17];
plot(x,y)

area(x,y)  %面积图

x=[0:2:18];           % 步长为2
y=[0,0.33,4.13,6.29,6.85,11.19,13.19,13.96,16.33,18.17];
plot(x,y)             % plot先,再添加图例,否则无效
title('实用1')        % 标题
xlabel('时间,min')   % x轴标注
ylabel('距离,ft')    % y轴标注
grid on               % 添加网格  grid off关闭
hold on               % 冻结当前窗口,继续添加图形 hold off关闭
y1=[8,5.33,4.13,6.69,7.85,10.19,11.69,13.96,16.33,19.67];
plot(x,y1)  


% 方法二
x=0:pi/100:2*pi;
y1=cos(x)*2;
y2=cos(x)*3;
y3=cos(x)*4;
y4=cos(x)*5;
plot(x,y1,x,y2,x,y3,x,y4);
% or
z=[y1;y2;y3;y4]
plot(x,z)

peaks(100)     % 双变量函数 矩阵

plot(peaks(100))

A=[0+0i,1+2i,2+5i,3+4i]
plot(A)
title('一个复数数组x的波形')        % 标题
xlabel('数组x的实部')   % x轴标注
ylabel('数组x的虚部')    % y轴标注


% 双复数,忽略虚部
A=[0+0i,1+2i,2+5i,3+4i]
B=sin(A)
plot(A,B)
title('双复数数组的波形')        % 标题
xlabel('数组x的实部')   % x轴标注
ylabel('数组y的实部')    % y轴标注

线型,标记,颜色,

在同一个坐标系内绘制多条曲线

命令: plot(x1,y1,arguments1,x2,y2,arguments2...)

说明: 参数arguments

配置:线型,线条宽度,颜色,标记类型,标记大小,标记面填充颜色,标记面周边颜色

线型

定义符----.
线型实线(默认值)虚线点线点划线

标记类型

定义符+o*.xd^ v < >
标记类型加号小圆圈星号实点交叉号菱形向(上小左左)三角
shp
正方形正六角星正五角星

颜色

标识符蓝色绿色红色青色洋红色黄色黑色白色
颜色bgrcmybw
x=[0:2:18];  %步长为2
y=[0,0.33,4.13,6.29,6.85,11.19,13.19,13.96,16.33,18.17];
plot(x,y,':ok')
hold on
plot(x,y*2,'LineWidth',1,'Marker','h','MarkerSize',12)
plot(x,y/2,'LineWidth',3,'Marker','d','MarkerSize',8)


% 坐标轴的缩放和图形的标注

clf   %清除图形
plot(x,y,':ok',x,y*2,'--xr',x,y/2,'-b')
legend('line1','line2','line3')
text(1,20,'这是一个文本框字符')   % 添加文本框
title('这是一个标题 \alpha x^2 x_5 k^{-1}')        % 标题
xlabel('x轴')        % x轴标注
ylabel('y轴')        % y轴标注
axis([0,20,0,30])   % 轴范围

% 多个子图
x=0:pi/20:2*pi;
subplot(2,2,2)   % 2行2列第2个
plot(x,sin(x))
subplot(2,2,3)   % 2行2列第3个
plot(x,sin(2*x))



% 极坐标图

x=0:pi/100:pi;
y=sin(x);
polarplot(x,y)  % 弧度,半径

clear,clc
x=[1,2,5,4,8];
y=[x;1:5];
subplot(2,2,1)
    bar(x)
subplot(2,2,2)
    bar(y)
subplot(2,2,3)
    bar3(y)
subplot(2,2,4)
    pie(x)

clear,clc
x=[100,95,74,87,22,78,34,82,93,88,86,69,55,72];
subplot(2,2,1)
   histogram(x)   % 自动分配
subplot(2,2,2)
   histogram(x,5) % 5个图形
subplot(2,2,3)    
   edges=[0,60,70,80,90,100]
   histogram(x,edges) % 自定义分组
subplot(2,2,4)
   histogram(x,edges,'normalization','countdensity') % 归一化,面积与该段数据的数量成正比

clear,clc,clf
x=0:pi/20:2*pi;
y1=sin(x)
y2=exp(x)
subplot(1,2,1)
   plot(x,y1,x,y2)
subplot(1,2,2)
    yyaxis left   
        plot(x,y1)
    yyaxis right
        plot(x,y2)
        

%--------------------元素周期性案例---------------------------%
        
 clear,clc,clf
x=[3,11,19,37,55]         % 原子序数
y1=[181,98,63,34,28.4]     % 熔点
y2=[0.152,0.186,0.227,0.248,0.265] % 原子半径
subplot(1,2,1)
   plot(x,y1,'-o',x,y2,'-x')
   xlabel('原子序数')   
   ylabel('熔点')    
subplot(1,2,2)
        plot(x,y1,'-o')
        xlabel('原子序数')   
        ylabel('熔点')  
    yyaxis right
        plot(x,y2,'-x')
        ylabel('原子半径,pm')  

clear,clc,clf
% @固定开头,用于指定自变量,绘图函数,第二个参数为区间
fplot(@(x)sin(x),[-2*pi,2*pi])  

% or
f=@(x) sin(x)
fplot(f,[-2*pi,2*pi])


三维曲线的绘制

plot3(x,y,z)绘制三维线图
comet3(x,y,z)绘制具有动画效果的三维线图
mesh(z)或mesh(x,y,z)绘制网格曲面图
surf(z)或surf(x,y,z)绘曲面图,与mesh函数类似
shading interp渲染曲面图中的颜色
shading flat用纯色给每个网格着色
colormap(map_name)按用户设定的颜色绘制曲面图
contour(z)或contour(x,y,z)绘制等高线图
contourf(z)或contourf(x,y,z)绘制填充的等高线图
surfc(z)或surfc(x,y,z)同时绘制曲面图和等高线图
pcolor(z)或pcolor(x,y,z)绘制伪彩色图

plot3命令将绘制二维图形的函数plot的性扩展到三维空间。函数格式除了包第三维的信息(比如Z方向)之外,与二维函plot相同。plot3一般语法的调用格式是(x1,y1,z1,S1,x2,y2,z2,S2,...),这里xn,yn和zn是向量或矩阵,Sn是可选的子符串,用指定颜色,标记符号,或线型。plot3可用来画一个单变量的三维函数

绘制一个三位螺旋线

t=0:pi/50:10*pi;
plot3(sin(t),cos(t),t)
title('Helix'),xlabel('sin(t)'),ylabel('cos(t)'),zlabel('t');
text(0,0,0,'Origin');
grid
v=axis;

三维网线图与表面图的绘制

命令格式:mesh(x,y,z)   %绘制三维网线图

 surf(x,y,z)      %绘制三维表面图

绘制曲线在区域[-2,2] x [-2,2]上的图形

x=-2:0.1:2;
y=-2:0.1:2;
[X,Y]=meshgrid(x,y);     %用x和y产生‘格点’矩阵
Z=cos(X.*Y);          %计算‘格点’矩阵的函数值
mesh(X,Y,Z)


x=-2:0.1:2;
y=-2:0.1:2;
[X,Y]=meshgrid(x,y);     %用x和y产生‘格点’矩阵
Z=cos(X.*Y);          %计算‘格点’矩阵的函数值
surf(X,Y,Z)

三维网图的高级处理

1.消隐处理

2.裁剪处理

虽然曲面图不能作成透明的,但在一些情况下以很方便地移走一部分表面以便看到表面以下的部分,在 MATLAB中,这是通过在所期望的洞孔的所在位置,将数据置为特定的NaN来实现。由于NaN没有任何值,所有的 MATLAB作图函数都忽略NaN的数据点,在该点出现的位置留下一个洞孔。

% 消隐处理
z=peaks(50);
subplot(2,1,1);
mesh(z)
title('消隐前的网图')
hidden off
subplot(2,1,2);
mesh(z)
title('消隐后的网图')
hidden on
colormap([0 0 1])

%-----------------------------------------------------------------%
% 图片裁剪处理

[X,Y,Z]=peaks(30);
x=X(1,:);
y=Y(:,1);
i=find(y>.8 & y<1.2);
j=find(x>-.6 & x<.5);
Z(i,j)=nan*Z(i,j);
surf(X,Y,Z)
grid
xlabel('x-axis'),ylabel('y-axis'),zlabel('z-axis');
title('SURF of PEAKS with a Hole')

clear,clc,clf
x=-2:0.2:2;
y=-2:0.2:2;
[X,Y]=meshgrid(x,y);     %用x和y产生‘格点’矩阵
Z=X.*exp(-X.^2-Y.^2);    %计算‘格点’矩阵的函数值

subplot(2,2,1)
    mesh(X,Y,Z)
    title('mesh图'),xlabel('z'),ylabel('y'),zlabel('z')    
subplot(2,2,2)
    surf(X,Y,Z)
    title('surf图'),xlabel('z'),ylabel('y'),zlabel('z')   
subplot(2,2,3)
    contour(X,Y,Z)
    title('等高线图'),xlabel('z'),ylabel('y'),zlabel('z')   
subplot(2,2,4)
    surfc(X,Y,Z)
    title('surf图与等高线图'),xlabel('z'),ylabel('y'),zlabel('z')   

clear,clc,clf
[X,Y,Z]=peaks;    % 示例函数peaks
subplot(2,2,1)
    pcolor(X,Y,Z)
    title('伪色图') 
subplot(2,2,2)
    pcolor(X,Y,Z)
    shading interp   % 插入阴影模式   shading flat
    title('插入阴影') 
subplot(2,2,3)
    pcolor(X,Y,Z)
    shading interp   %
    hold on
    contour(X,Y,Z,20,'k')   %20条等高线,k代表黑色
    hold off
  title('伪色与等高线图叠加') 
subplot(2,2,4)
    contour(X,Y,Z)
    h=contour(X,Y,Z);
    clabel(h)
    title('标记的等高线图') 

clear,clc,clf
x=5:30;
y=x.^2-40.*x+400;
plot(x,y)
axis([5,30,-50,250])
[a,b]=ginput          % 鼠标右键 按回车
clear,clc,clf

x=[0.1,1,1.5,2];  x1=0.8667;
y=[2,1,0.2,2];    y1=1.6125;
z=[3,1,0.5,4];    z1=2.5723;
plot3(x,y,z,'o',x1,y1,z1,'s')
grid on
axis([0,2,0,2,0,4])

逻辑函数

clear,clc,clf
height=[63,45,95,26,78,65,61,59,65]
accept=find(height>=65)   % find 搜索满足条件的矩阵,返回下标
height(accept)
clear,clc,clf

a=25;
b=20:20:80;
if a<50
    disp('G is a small value equal to:')
    disp(a)
end

if b<50   % 非标量,全为真才执行
    disp('G is b small value equal to:')
    disp(b)
end
age=[15,17,25,55,75];
if age<16
    disp('16')
elseif age<18
    disp('18')
elseif age<70
     disp('70')
else
    beep     % 发出提示音
    disp('age is a small value equal to:')
end
clear,clc,clf

city=input('请输入:')
switch city
    case 'Boston'
        disp('$324')
    case 'Denver'
        disp('$324')
    case 'New York'
        disp('$624')
    otherwise
        disp('Not on file')
end


clear,clc,clf
% menu 图形界面菜单
city=menu('Select a city from the menu:','Boston','Denver','New York');
switch city
    case 1
        disp('$324')
    case 2
        disp('$324')
    case 3
        disp('$624')
    otherwise
        disp('Not on file')
end

循环结构

scores=[76,45,98,97]
count=0
for k=1:length(scores)
    if scores(k)>90
        count=count+1;
    end
end
disp(count)
clear,clc,clf

n=0;
a=1;
while(n<10)
    n=n+1;
    if(a>=0)
        disp('test')
     continue % 跳过当前循环,继续下一轮循环
     break   % 提前终止循环
    end
   disp('this is a test') 
end

数值计算方法

插值

clear,clc,clf
x=0:5; 
y=[15,10,9,6,2,0];
new_x=0:0.2:5;
new_y=interp1(x,y,new_x)   % 多点插值
plot(x,y,new_x,new_y,'o')
hold on
y1=interp1(x,y,3.5,'linear') 
plot(3.5,y1,'g*')% 单点线性插值


%---------------三次样条插值-------------------%
clear,clc,clf
x=0:5; 
y=[15,10,9,6,2,0];
new_x=0:0.2:5;
new_y=interp1(x,y,new_x,'spline')   % 三次样条插值
plot(x,y,new_x,new_y,'-o')
hold on
y1=interp1(x,y,3.5,'linear') 
plot(3.5,y1,'g*')% 单点线性插值

曲线拟合

线性回归

clear,clc,clf
x=0:5; 
y=[15,10,9,6,2,0];
polyfit(x,y,1)  % 1 代表直线是一阶
 % ans =-2.9143   14.2857
best_y=-2.9143*x+14.2857
new_sum=sum((y-best_y).^2) % 计算平方和
plot(x,y,'o',x,best_y)
title('线性回归的最优拟合')

%-------------过零点线性回归-------------%
clear,clc,clf
x=[0,10,20,30,40,50];  % 风速
y=[0,24,38,64,82,90];	% 产生的力
polyfit(x,y,1)  % 1 代表直线是一阶
 % ans =1.8571    3.2381
best_y=1.8571*x+3.2381
a=x'\y';  % 左除强制该模型过零点
y1=a(1)*x;
plot(x,y,'o',x,best_y,x,y1)
legend('数据点','Polyfit拟合结果','左除运算结果')
title('风洞实验结果')

clear,clc,clf
x=0:5; 
y=[15,10,9,6,2,0];
smooth_x=0:0.2:5;
for k=1:4
    subplot(2,2,k)
    % polyval 跟据回归条件,返回最佳拟合多项式系数,需要两个参数
    % 第一参数类似polyfit的系数数组,第二个是x数组,用来重新计算y值
    plot(x,y,'o',smooth_x,polyval(polyfit(x,y,k+1),smooth_x))
    axis([0,6,-5,15])
    a=sprintf('%1.0f阶模型\n',k+1)
    title(a)
end

clear,clc,clf
X=-2:.1:2; 
Y=-2:.1:2;
[x,y]=meshgrid(X,Y);
z=3*(1-x).^2.*exp(-(x.^2)-(y+1).^2)...
    -10*(x/5-x.^3-y.^5).*exp(-x.^2-y.^2)...
    -1/3*exp(-(x+1).^2-y.^2);
subplot(1,2,1)
    surf(x,y,z)
    title('peaks函数')
[dzdx,dzdy]=gradient(z,X,Y)
subplot(1,2,2)
    contour(x,y,z)
    hold on
    quiver(x,y,dzdx,dzdy)
     title('peaks函数的偏导数')