一、矩形建立

1、直接法

a=[1,2,3;4,5,6];% 相同行是逗号,不同行分号或空格

2、拼接法

a=[1,2;3,4];
b=[5,6;7,8];

c=[a;b]; %拼接矩阵是竖向相接的
1 2

3 4

5 6

7 8

c=[a,b]; %拼接矩阵是横向相接的
1 2 5 6

3 4 7 8

总结:要将两个行向量 A 和 B 拼接成一个行向量 C,可以使用以下语法: C = [A, B]       

如果想要将两个列向量 A 和 B 拼接成一个列向量 C,可以使用以下语法: C = [A; B]

3、冒号表达式

a=[1:2:10]; % 1为初始值,2为步长,可以不写,10为终止值,省略时,默认生成100个元素
a =
1 3 5 7 9

总结: 冒号表达式可产生一个由a开始到c结束,以步长b自增的行向量。

4、使用函数建立矩阵

4-1、zeros()与ones();

a=zeros(m);% 建立一个mm的矩阵
a=zeros(m,n);% 建立一个mn的矩阵
a=zeros(size(a));% 建立一个与a同样大小的矩阵
zeros()与ones()建立方法相同一个全为0一个全为1

4-2、rand();称为随机矩阵,按下回车键即可生成一个到1之间的随机数

a=rand(4,5); %生成一个区间在0-1的四行五列的矩阵
a =

0.8959 0.7725 0.2101 0.1015 
0.4317
0.0991 0.3119 0.5102 
0.3909 0.9976
0.0442 0.1790 
0.9064 0.0546 0.8116
0.5573 
0.3390 0.6289 0.5013 0.4857

4-3、eye();称为单位矩阵

eye(5); %生成一个5*5的矩阵
ans =

1 0 0 0 0

0 1 0 0 0

0 0 1 0 0

0 0 0 1 0

0 0 0 0 1

二、矩阵元素提取

提前赋值

1、单个赋值
a=[1,2,3;4,5,6];
a(3,2)=200;%当行列下标大于原来矩阵的行列时,matlab将自动扩展原来的矩阵,并把扩展后为赋值
的元素置于0

a(3);

a(1,2); %矩阵元素按列存储 ans=2
2、多个赋值-可以用冒号表达式实现
a(i,:);%表示a矩阵的第i行的全部元素
a(:,j);%表示a矩阵的第j列的全部元素

a(i:i+m,k:k+m);%表示a矩阵的ii+m行嵌在kk+m列元素的的全部元素
a(i,i:end);%运算符表示从当前元素i到最后一个元素的所有值
3、置空
a=[]; %表示空矩阵

删除矩阵中的元素

a(:,[2,4])=[];%删除A的第2列和第4列
a=rand(5)

a =

0.8944 0.7136 0.7306 0.8352 0.3304

0.1375 0.6183 0.6465 0.3225 0.6195

0.3900 0.3433 0.8332 0.5523 0.3606

0.9274 0.9360 0.3983 0.9791 0.7565

0.9175 0.1248 0.7498 0.5493 0.4139

a(:,[2,4])=[]

a =

0.8944 0.7306 0.3304

0.1375 0.6465 0.6195

0.3900 0.8332 0.3606

0.9274 0.3983 0.7565


0.9175 0.7498 0.4139

三、矩阵运算

  • 基本算术运算符:+(加)、-(减)、*(乘)、/(右除)、(左除)、^(乘方)。
  • MATLAB的除法运算分为右除和左除。
  • MATLAB的算术运算是在矩阵意义下进行的。
  • 单个数据的算术运算只是矩阵运算的一种特例。
  • 算数运算>关系运算>逻辑运算。
  • 要求同纬度,元素的个数必须相同,否则会提示矩阵的维数或大小不匹配。

1、算术运算

1-1、加减法

a=[1,2;3,4];
b=[5,6;7,8];

c=a+b;
  6 8
10 12
c=a-1;
0  1
2  3

1-2、乘法

  • 矩阵A的行数与矩阵B的列数相同;
  • 矩阵C的行数等于矩阵A的行数,矩阵C的列数等于矩阵B的列数;
  • 矩阵C的第m行n列元素值等于矩阵A的m行元素与矩阵B的n列元素对应值积的和。
a=[1,2;3,4];
b=[5,6;7,8];

c=a*b;

%1*5+2*7 1*6+2*8
%3*5+4*7 3*6+4*8
%矩阵a的第1行第1个矩阵元素*矩阵a的第1列第1个矩阵元素+矩阵a的第1行第2个矩阵元素*矩阵a的第
1列第2个矩阵元素,以此类推
        19 22
        43 50


1-3、除法

  • 除法运算分为右除‘和左除\
  • 计算左除A\B时,A的行数要与B的行数一致,计算右除A/B时,A的列数要与B的列数一致。
  • 如果A矩阵是非奇异方阵,则B/A等效于B * inv(A),A\B等效于inv(A)*B。
  • 对于矩阵来说,右除和左除表示两种不同的除数矩阵和被除数矩阵的关系
a=[1,2;3,4];
b=[5,6;7,8];

c=a\b;


-3 -4

 4  5

c=a/b;

3.0000 -2.0000

2.0000 -1.0000

1-4、乘方

a=[1,2;3,4];
c=a^2; %a为矩阵,2为标量相当于[1,2;3,4]*[1,2;3,4]
7 10

15 22

1-5、点运算

符号

说明


.*

对应元素相乘


./

对应元素进行左除


.\

对应元素进行右除


.^

对应元素进行乘法运算,指数和底都可以是标量


2、关系运算

1为真-true

0为假-false

符号

函数

说明

<

lt

小于

<=

le

小于等于

>

gt

大于

>=

ge

大于等于

==

eq

等于

~=

ne

不等于

注: 这些关系运算符还能用来比较两个同维矩阵,实际上是比较两个矩阵对应的元素,比较结果仍然是一个矩阵. 如果两个矩阵的对应元素符合某个关系,则结果矩阵对应的元素为1,否则为0

3、逻辑运算

符号

函数

解释

结果

&

and(a,b)

有0为0,全1为1

|

or(a,b)

有1为1,全0为0

~

not(a)

1变0,0变1


xor(a,b)

异或

相同为0,不同为1

1、当是矩阵时比较的是矩阵相同位置的元素,产生一个由0和1组成的矩阵

2、当参与比较的一个是标量,一个是矩阵,则标量与矩阵的每一个元素进行比较,产生一个由0和1组成的矩阵

3、逻辑非是单目运算符,也服从矩阵运算规则

4、矩阵的旋转与转置

符号

函数

说明

旋转

rot90(A,K)

矩阵A旋转90度的K倍

转置

.'

矩阵的行列进行互换

上下旋转

flipud()

矩阵的行相互调换

左右旋转

fliplr()

矩阵的列相互调换

第二章、数值分析(数据分析与多项式计算)

在命令提示框中输入 help 函数 ,可获得该函数的提示信息

help rand;

1、数据分析

1-1、矩阵的最大值与最小值

x2=[13,-56,75;25,63,-253;1,0,-1];
max(x2); %输出列的最大值

ans =
25 63 75

max(max(x2));%输出矩阵的最大值
ans =
75

max(x2,[],2);%输出行的最大值,1表示列,可以省略,2表示行,不可以省略

ans =
75

         63

          1

[y,k]=max(x2);%y表示最大值,k表示最大值的序号

y =

25 63 75

k =
2 2 1

1-2、求和、求积

x3=[1 2 3];
sum(x3);

prod(x3);

x4=[1 2 3;4 5 6];

sum(x4); % 输出每一列的和

ans =
5       7       9

sum(sum(x4)); %输出矩阵的和

ans =

          21

sum(x4,2); % 输出每一行的和,1表示列,可以省略,2表示行,不可以省略

ans =
6

         15

prod(x4); %输出每一列的积

ans =
4      10       18

prod(prod(x4)); %输出矩阵的积

ans =  
       720

1-3、平均值、中值

x=[9 -2 5 6 7 12];
mean(x); % 求平均值和期望的函数
ans =
6.1667
median(x); %求中值的函数
ans =
6.5000
x2=[1 2; 5 6];mean(x2); %每一列的平均值
ans =
3 4
mean(x2,2); %求每一行的平均值,1表示列,可以省略,2表示行,不可以省略
ans =
1.5000
5.5000

1-4、排序

[Y,I]=sort(A,dim,made
  1. Y表示排序后的矩阵
  2. I表示Y的元素在A中的位置,可以省略
  3. A表示矩阵 ,dim表示 行(2)列(1)
  4. mode表示升序(ascend)和降序(descend),默认是升序(ascend)
A=[1 -8 5; 4 12 6; 13 7 -13];
sort(A,1,'descend') %表示使矩阵A的列,按降序排序
ans =
13 12 6
4 7 5
1 -8 -13

2、多项式的计算

可以使用复数

A=[1 -8 5;2+2*j,2+2*j,4+4*j];
A =
1.0000 + 0.0000i -8.0000 + 0.0000i 5.0000 + 0.0000i
2.0000 + 2.0000i 2.0000 + 2.0000i 4.0000 + 4.0000i

2-1、多项式的四则运算

2-1-1、加减运算
a=[1 -2 5 3];
b=[0 0 6 -1];
c=a+b;
c =
1 -2 11 2
c=a-b;
c =
1 -2 -1 4
2-1-2、乘法运算
a=[1 8 0 0 -10];
b=[2 -1 3];
c=conv(a,b);
c =
2 15 -5 24 -20 10 -30
2-1-3、除法运算
a=[1 8 0 0 -10];
b=[2 -1 3];
[P,r]=deconv(a,b); % P表示商数 r表示余数
P =
0.5000 4.2500 1.3750
r =
0 0 0 -11.3750 -14.1250

2-2、数据插值

2-2-1、plot函数参数

绘制二维线图

plot(x,y,'颜色线型标记符号',x1,y1,'选项1',x2,y2,'选项2', ... ,xn,yn,'选项n')
  1. 如果 X 和 Y 都是向量,则它们的长度必须相同
  2. 如果 X 和 Y 均为矩阵,则它们的大小必须相同
  3. 当x是向量,y是矩阵时,x的长度与矩阵y的行数或列数必须相等。
  4. 如果x的长度等于y的行数,则以x和y的每列为横、纵坐标绘制曲线,曲线的条数等于y的列数。
  5. 如果x的长度等于y的列数,则以x和y的每行为横、纵坐标绘制曲线,曲线的条数等于y的行数。
  6. 如果y是方阵,x的长度和矩阵y的行数或列数都相等,则以x和y的每列为横、纵坐标绘制曲线
  7. 如果 X 或 Y 一个为标量,而另一个为标量或向量,则 plot 函数会绘制离散点。但是,要查看这些点,必须指定标记符号
  8. 线型、标记和颜色,指定为包含符号的字符向量或字符串,符号可以按任意顺序显示,不需要同时指定所有三个特征

选项

全称

线性

-(默认)

solid

实线

dotted

点线

-.

dashdot

点画线

-.

dashed

虚线

选项

全称

颜色

b

blue

蓝色

g

green

绿色

r

red

红色

c

cyan

墨绿色

m

magenta

紫红色

y

yellow

黄色

k

black

黑色

选项

全称

标记符号

none(默认)


不显示

.

point

o (字母)

circle

圆圈

x (字母)

x-mark

叉号

+

plus

加号

*

star

星号

s

square

正方形

d

diamond

菱形

v(字母)

triangle

down 下

^

triangle

up 上

<

triangle

left 左

>

triangle

right 右

p

pentagram

五角星

h

hexagram

六角形

x=[0 3 5 7 9 11 12 13 14 15];
y=[0 1.2 1.7 2.0 2.1 2.0 1.8 1.2 1.0 1.6];
subplot(2,3,1); % 2表示是图排成2行,3表示图排成3列,1表示图所在的位置,表示从左到右从上
到下的第一个位置。
plot(x,y,'r-o');

第一章基础_标量

2-3、一维数据插值

x=[0 3 5 7 9 11 12 13 14 15];
3、y=2e^{-0.5x}sin(2\pix)
y=[0 1.2 1.7 2.0 2.1 2.0 1.8 1.2 1.0 1.6];
subplot(2,3,1);
plot(x,y,':ro');
x1=0:00.1:15;
y1=interp1(x,y,x1,'linear');
subplot(2,3,2);
plot(x1,y1,':bo');
y2=interp1(x,y,x1,'nearest');
subplot(2,3,3);
plot(x1,y2,':yo');
y3=interp1(x,y,x1,'pchip');%第三次艾米尔特差值
subplot(2,3,4);
plot(x1,y3,':ko');
y4=interp1(x,y,x1,'spline');%三次样调差值
subplot(2,3,5);
plot(x1,y4,':go');

第一章基础_表示图_02

2-3-1、y=2e^{-0.5x}sin(2\pix)
x=0:0.01:2*pi;
y=2.*exp(-0.5*x).*sin(2*pi*x);
plot(x,y,'-or');
xlabel('variable x'); %x轴图例
ylabel('variable y'); %y轴图例
legend('曲线y'); %图例
title('正弦震荡衰减函数'); %标题
text(2,1,'y=2e^{-0.5x}sin(2\pix)');%表达式

第一章基础_标量_03

2-3-2、y=2e^{-0.5x} 下包路 y=-2e^{-0.5x}
x=0:0.01:2*pi;
y=2.*exp(-0.5*x).*sin(2*pi*x);
y1=2.*exp(-0.5*x);
y2=-2.*exp(-0.5*x);
plot(x,y,'-or');
hold on %图像不覆盖函数
plot(x,y1,':r');
plot(x,y2,':r');
xlabel('variable x');
ylabel('variable y');
legend('曲线y');
title('正弦震荡衰减函数');
text(2,1,'y=2e^{-0.5x}sin(2\pix)');

第一章基础_标量_04

2-3-3、subplot()函数
x=0:0.01:2*pi;
y=2.*exp(-0.5*x).*sin(2*pi*x);
y1=2.*exp(-0.5*x);
6、自适应采样 cos(tan(pi*x))
y2=-2.*exp(-0.5*x);
subplot(2,2,1); % 2表示是图排成2行,2表示图排成2列,1表示图所在的位置,表示从左到右从上到下
的第一个位置。
plot(x,y,'-or');
subplot(2,2,2);
plot(x,y,'-or');
subplot(2,2,3);
plot(x,y,'-or');
subplot(4,4,11);
plot(x,y,'-or');
hold on
plot(x,y1,':r');
plot(x,y2,':r');
xlabel('variable x');
ylabel('variable y');
legend('曲线y');
title('正弦震荡衰减函数');
text(2,1,'y=2e^{-0.5x}sin(2\pix)');

第一章基础_标量_05

2-3-4、自适应采样 cos(tan(pi*x)
x=0:0.01:1;
y=cos(tan(pi*x));
subplot(2,1,1);
plot(x,y);
subplot(2,1,2);
f=@(x)cos(tan(pi*x));
fplot(f,[0,1]); %自适应采样函数

第一章基础_标量_06

2-3-5、对数坐标系
clear %清除工作区数据
x=0:2:10;
y = 10 * x .* x;
subplot(2,2,1);
plot(x,y,'-or');
subplot(2,2,2);
semilogy(x,y,'-ob');
subplot(2,2,3);
semilogx(x,y,'-oy');

第一章基础_表示图_07

第三章、三维绘图

3-1、三维曲线

eg 绘制三维曲线 :

x=cos(t)

y=sin(t) z=2t

t = 0 : 0.1 :6*pi;
x = cos(t);
y = sin(t);
z = 2 * t;
plot3(x,y,z,'r-');
xlabel('X');ylabel('Y');zlabel('Z');

第一章基础_MATLAB_08

3-2、三维曲面

eg 绘制 Z=sin(y)cos(x)

mesh :线条间无颜色,线条有颜色

x = 0 : 0.1 :2*pi;
y = 0 : 0.1 :2*pi;
[X,Y]=meshgrid(x,y);
Z=sin(Y).*cos(X);
subplot(1,2,1);
mesh(X,Y,Z)

第一章基础_表示图_09

surf:线条间有颜色,线条黑色
x = 0 : 0.1 :2*pi;
y = 0 : 0.1 :2*pi;
[X,Y]=meshgrid(x,y);
Z=sin(Y).*cos(X);
subplot(1,2,1);
mesh(X,Y,Z);
surf(X,Y,Z);

第一章基础_标量_10

meshc:带等高线

meshz:带底座

surfc:带等高线

surfl:光照效果

s(1).......访问曲面对象

s(1).......访问光照对象

x = 0 : 0.1 :2*pi;
y = 0 : 0.1 :2*pi;
[X,Y]=meshgrid(x,y);
Z=sin(Y).*cos(X);
subplot(4,1,1);
meshc(X,Y,Z);
subplot(4,1,2);
meshz(X,Y,Z);
subplot(4,1,3);
surfc(X,Y,Z);
subplot(4,1,4);
s=surfl(X,Y,Z,'light');
s(2).Color = 'r';

第一章基础_MATLAB_11

3-3、面向句柄

handle_plot = plot(x,y,'r')

plot(x,y,'r') 绘制二维曲线,同时返回曲线对象的句柄(句柄可以控制曲线对象)

x = 0 : 01 :2*pi;
y=2*exp(-0.5*x).*sin(2*pi*x);
handle_plot = plot(x,y,'r');
x = 0 : 0.01 :2*pi;
y=2*exp(-0.5*x).*sin(2*pi*x);
handle_plot = plot(x,y,'r-');
set(handle_plot,'Color','b');
set(handle_plot,'LineStyle',':');

第一章基础_标量_12

第四章、程序结构,函数

输入和输出函数

input %

4-1、选择结构

4-1-1、if end 单分支

x=input("请输入成绩:");
if x<=100 && x>=60
disp('pass the exam');
end
if x<60
disp('渣渣');
end

4-1-2、if else end 双分支

x=input("请输入成绩:");
if x<=100 && x>=60
disp('pass the exam');
else
disp('渣渣');
end

4-1-3、if elseif .... elseif else end 多分支

x=input("请输入成绩:");
if x<=100 && x>=90
disp('level A');
elseif x<=90 && x>=80
disp('level B');
elseif x<=80 && x>=70
disp('level C');
elseif x<=70 && x>=60
disp('level D');
else
disp('渣渣');
end

4-1-4、switch case ... case otherwise end

x=input("请输入成绩:");
switch floor(x/10)
case{10,9}
disp('level A');
case 8
disp('level B');
case 7
disp('level C');
case 6
disp('level D');
otherwise
disp('渣渣');
end

4-2、循环结构

4-2-1、for end

fz=1;
t=0;
for i=1:100
t=t+fz/(i*i);
end
disp(t);

4-2-2、while end

y = 0;
n=100;
i=1;while i<=100
y=y+1/(i*i);
i=i+1;
end
disp(y);
for n=100:200
if rem(n,21)~=0
continue;
end
disp(n);
break
end

4-3、函数

4-3-1、函数的建立

  • 如果 M 文件的第一个可执行语句以 function 开始,该文件就是函数文件,每一个函数文件都定义一个函数。
  • 函数文件区别于脚本文件之处在于脚本文件的变量为命令工作空间变量,在文件执行完成后保留在命令工作空间中;而函数文件内定义的变量为局部变量,只在函数文件内部起作用,当函数文件执行完后,这些局部变量将被清除。
  • 建立函数文件时,函数定义名应和文件保存名一致。当两者不一致时, MATLAB 将忽视文件首行的函数定义名,而以文件保存名为准。
  • MATLAB 中的函数文件名必须以字母开头,可以是字母、下画线及数字的任意组合,但不可超过31 个字符。
  • 关于注释说明部分。注释说明包括如下 3 部分内容。
  • 紧随函数文件引导行之后以 % 开头的第一注释行。这一行一般包括大写的函数文件名和函数 功能简要描述,供 lookfor 关键词查询和 help 在线帮助用。
  • 第一注释行及之后连续的注释行。通常包括函数输入输出参数的含义及调用格式说明等信息,构成全部在线帮助文本。
  • 与在线帮助文本相隔一空行的注释行。包括函数文件编写和修改的信息,如作者、修改日期、版本等内容,用于软件档案管理。 初始文件内容如下:
function [outputArg1,outputArg2] = untitled9(inputArg1,inputArg2)
%UNTITLED9 此处显示有关此函数的摘要
% 此处显示详细说明
outputArg1 = inputArg1;
outputArg2 = inputArg2;
end
4-3-1-1、普通函数

函数由关键字 function 引导,指明这是一个函数文件,并定义函数名、输入参数和输出参数。

函数定义行 必须为文件的第一个可执行语句, 函数名与文件名相同,可以是MATLAB 中任何合法的字 符。 函数文件可以带有多个输入参数和输出参数,如:

function 输出形参表 = 函数名(输入形参表) % 参数使用逗号隔开,返回参数多余一个时,使用[]括起
来
% 注释说明部分
函数体语句
function [s,p] = untitled9(r)
% r ---- 半径
% s ---- 面积
% p ---- 周长
s=pi*r*r;
p=2*pi*r;
end
4-3-1-2、匿名函数

匿名函数没有函数名,也不是函数 M 文件,只包含一个表达式和输入 / 输出参数。用户可以通过在命令

行窗口中输入代码来创建匿名函数。

  1. 它由单个MATLAB表达式和任意数量的输入和输出参数组成。
  2. 可以在MATLAB命令行或函数或脚本中定义一个匿名函数。
  3. 这样就可以创建简单的函数,而无需为它们创建一个文件。 匿名函数的创建方法为:
f = @(arglist)expression
f= @ (输入参数) 表达式 % @是创建函数句柄的运算符,@后面定义了一个匿名函数,参数间用逗号分隔
>> f=@(x,y)x^2+y^2; %定义匿名函数
>> f(3,4) %调用匿名函数
ans =
25

4-3-2、函数的调用

  • 函数调用时要注意各实参出现的顺序,个数,应于函数定义时的形参的顺序,个数一致,否则会出错
  • 函数可以嵌套调用,既一个 函数可以调用嵌套函数,甚至调用他自身,一个函数调用它自身称为函数的递归调用
  • 函数调用时,先将实参传递给相应的形参,从而实现参数传递,然后再执行函数的功能。
[输出实参表]=函数名(输入实参表)
[s,p] = untitled9(5)
s =
78.5398
p =
31.4159

4-4、程序的调用和优化

4-4-1、利用调试函数进行程序测试

MATLAB 提供了一系列的程序调试函数,用于程序执行过程中的断点操作、执行控制等。在 MATLAB

命令行窗口输入以下命令将输出调试函数及其用途简介。

>> help debug

常用的调试函数有以下几个。

(1) dbstop :在程序的适当位置设置断点,使得系统在断点前停止执行,用户可以检查各个变量的 值,从而判断程序的执行情况,帮助发现错误。使用以下命令可以显示 dbstop 函数的常用格式。

>> help dbstop

(2) dbclear :清除用 dbstop 函数设置的断点。

(3) dbcont :从断点处恢复程序的执行,直到遇到程序的其他断点或错误。

(4) dbstep :执行一行或多行语句,执行完后返回调试模式,如果在执行过程中遇到断点,程序将 中止。

(5) dbquit :退出调试模式并返回到基本工作区,所有断点仍有效。

4-4-2、利用调试工具进行调试

控制单步运行的命令共有 4 个。在程序运行之前,有些命令按钮未激活。只有当程序中设置了断点,且

程序停止在第一个断点处时这些命令按钮才被激活,这些命令按钮功能如下。 (1) 步进:单步运行。每单击一次,程序运行一条语句,但不进入函数。

(2) 步入:单步运行。遇到函数时进入函数内,仍单步运行。

(3) 步出:停止单步运行。如果是在函数中,跳出函数;如果不在函数中,直接运行到下一个断点 处。

(4) 运行到光标处:直接运行到光标所在的位置。

4-4-3、程序性能分析

利用探查器(Profiler)、 tic 函数和 toc 函数能分析程序各环节的耗时情况,分析报告能帮助用户寻找

影响程序运行速度的瓶颈所在,以便于进行代码优化。 探查器以图形化界面让用户深入地了解程序执行过程中各函数及函数中的每条语句所耗费的时间,从而 有针对性地改进程序,提高程序的运行效率。

在 MATLAB 的命令行窗口输入以下命令:

>> profile on
>> testp
>> profile viewer

MATLAB 将打开探查器窗口,显示分析结果。探查摘要表提供了运行文件的时间和相关函数的调用频率,反映出整个程序耗时 2.626s,其中绘制图形中调用的 newplot 函数耗时最多。单击某函数名,则 打开相应函数的详细报告。

4-4-4、程序优化

MATLAB 是解释型语言,计算速度较慢,所以在程序设计时如何提高程序的运行速度是需要重点考虑的问题。优化程序运行可采用以下方法。

(1) 采用向量化运算。在实际 MATLAB 程序设计中,为了提高程序的执行速度,常用向量或矩阵运算 来代替循环操作。首先生成一个向量 i i i,然后用 i i i 生成向量 f f f, f f f 各元素值即对应于 y y y 的各 累加项,再用 MATLAB 提供的 sum 函数求f各个元素之和。程序如下:

n=100;
i=1:n;
f=1./(i.*i);
y=sum(f)

如果程序中的 n 值由 100 改成 100000,再分别运行这两个程序,则可以明显地看出,用向量计算方法编写的程序比循环程序要快得多。

(2) 预分配内存空间。通过在循环之前预分配向量或数组的内存空间可以提高 for 循环的处理速度。例如,下面的代码用函数 zeros 预分配 for 循环中用到的向量 a 的内存空间,使得这个 for 循环的运 行速度显著加快。

程序 1:

clear;
a=0;
for n=2:1000a(n)=a(n-1)+10;
end

程序 2:

clear;
a=zeros(1,1000);
for n=2:1000a(n)=a(n-1)+10;
end

程序 2 采用了预定义矩阵的方法,运行时间比程序 1 要短。

(3) 减小运算强度。在实现有关运算时,尽量采用运算量更小的运算,从而提高运算速度。一般来 说,乘法比乘方的运算快,加法比乘法运算快。例如:

clear;
a=rand(32); %生成一个32×32矩阵
x=a.^3;
y=a.*a.*a;

第五章、Matlab图形用户界面设计

5-1、GUI设计过程

在命令行窗口输入guide

>> guide

第一章基础_MATLAB_13

第一章基础_MATLAB_14

5-3、设计步骤

5-3-1、初始界面

第一章基础_表示图_15

5-3-2、过程

在使用时可以选择按钮,进行拖动,可选择按钮

第一章基础_MATLAB_16

第一章基础_标量_17

5-3-3、代码功能实现

在.m文件中选择按钮所对应的函数,实现相对应的功能

在GUI设计界面,选择按钮,右键,选择查看回调,选择Callback,跳转对应的函数

function pushbutton1_Callback(hObject, eventdata, handles)
% step1 获取当前按钮上的String值
s = get(hObject,'string');
% step2 设置按钮功能,使点击按钮时,按钮的值加一
set(hObject,'string',num2str(str2num(s)+1));
% --- Executes on button press in pushbutton2.
function pushbutton2_Callback(hObject, eventdata, handles)
close all;
clear; %关闭打开的图形界面

5-4、计算器实例

guide 打开GUI设计界面
str2num(); 字符转数字
num2str(); 数字转字符
mcc -m untitled1 生成一个文件名为untitled1.exe的文件,同时生成相应参数
mcrinstaller 查找.EXE文件
>> eval('1+2+5*2') 计算字符型的数据,值为int类型
ans =
13

5-4-1、.m文件

% --- Executes on button press in pushbutton2. 2
function pushbutton2_Callback(hObject, eventdata, handles)
s0 =get(handles.text2,'string');
s =get(hObject,'string');
set(handles.text2,'string',[s0,s]);
% --- Executes on button press in pushbutton3. 3
function pushbutton3_Callback(hObject, eventdata, handles)
s0 =get(handles.text2,'string');
s =get(hObject,'string');
set(handles.text2,'string',[s0,s]);
% --- Executes on button press in pushbutton4. 4
function pushbutton5_Callback(hObject, eventdata, handles)
s0 =get(handles.text2,'string');
s =get(hObject,'string');
set(handles.text2,'string',[s0,s]);
% --- Executes on button press in pushbutton5. 5
function pushbutton6_Callback(hObject, eventdata, handles)
s0 =get(handles.text2,'string');
s =get(hObject,'string');
set(handles.text2,'string',[s0,s]);
% --- Executes on button press in pushbutton6. 6
function pushbutton7_Callback(hObject, eventdata, handles)
s0 =get(handles.text2,'string');
s =get(hObject,'string');
set(handles.text2,'string',[s0,s]);
% --- Executes on button press in pushbutton7. 7
function pushbutton8_Callback(hObject, eventdata, handles)
s0 =get(handles.text2,'string');
s =get(hObject,'string');
set(handles.text2,'string',[s0,s]);
% --- Executes on button press in pushbutton8. 8
function pushbutton9_Callback(hObject, eventdata, handles)
s0 =get(handles.text2,'string');
s =get(hObject,'string');
set(handles.text2,'string',[s0,s]);
% --- Executes on button press in pushbutton9. 9
function pushbutton10_Callback(hObject, eventdata, handles)
s0 =get(handles.text2,'string');
s =get(hObject,'string');
set(handles.text2,'string',[s0,s]);
% --- Executes on button press in pushbutton10. 0
function pushbutton4_Callback(hObject, eventdata, handles)
s0 =get(handles.text2,'string'); %获取名为text2的文本框的界面字符
s =get(hObject,'string'); %获取当前按钮点击字符
set(handles.text2,'string',[s0,s]); %在名为text2的文本框中显示获取的字符,并把获取的两个
数据练习起来
% --- Executes on button press in pushbutton11. 加
function pushbutton12_Callback(hObject, eventdata, handles)
s0 =get(handles.text2,'string');
s =get(hObject,'string');
set(handles.text2,'string',[s0,s]);
% --- Executes on button press in pushbutton12. 减
function pushbutton13_Callback(hObject, eventdata, handles)
s0 =get(handles.text2,'string');
s =get(hObject,'string');
set(handles.text2,'string',[s0,s]);
% --- Executes on button press in pushbutton13. 乘
function pushbutton14_Callback(hObject, eventdata, handles)
s0 =get(handles.text2,'string');
% s =get(hObject,'string');
set(handles.text2,'string',[s0,'*']); %设置乘法的符号,使之可以使eval函数识别
% --- Executes on button press in pushbutton14. 除
function pushbutton16_Callback(hObject, eventdata, handles)
s0 =get(handles.text2,'string');
s =get(hObject,'string');
set(handles.text2,'string',[s0,s]);
% --- Executes on button press in pushbutton15. 等于号
function pushbutton17_Callback(hObject, eventdata, handles)
s0 = get(handles.text2,'string'); %获取点击事件,确定是否计算数值
set(handles.text2,'string',num2str(eval(s0))); %设置计算的方法,使用eval函数计算s0所
获取到的数,之后使计算后的值从int类型转换为string类型,打印在名为text2的文本框中
% --- Executes on button press in pushbutton16. 清除
function pushbutton18_Callback(hObject, eventdata, handles)
set(handles.text2,'string',[]); %使text2文本框中的值为空

5-4-2、GUI设计界面

第一章基础_MATLAB_18

5-4-3、实现结果成功图显示

第一章基础_标量_19

5-5、实现从动态文本框获取数据

5-5-1、GUI设计界面

第一章基础_标量_20

5-5-2、代码实现

function edit1_Callback(hObject, eventdata, handles)
% hObject handle to edit1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of edit1 as text
% str2double(get(hObject,'String')) returns contents of edit1 as a double
s0 =get(handles.edit1,'string'); %获取可编辑文本框中的数据
set(handles.text2,'string',s0); %把获取的数据从静态文本框中输出
% --- Executes during object creation, after setting all properties.
function edit1_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'),
get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end

5-5-3、实现结果

第一章基础_表示图_21

5-6、实现获取信息从列表框中输出

5-6-1、GUI设计界面

第一章基础_表示图_22

5-6-2、代码功能实现

% --- Executes on button press in pushbutton1.
function pushbutton1_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
name = get(handles.edit1,'string'); %获取编辑框信息
% 获取第一个弹出框所选内容
xingbie = get(handles.popupmenu1,'string'); % 获取按钮的列表项
v1 = get(handles.popupmenu1,'value'); % 获取选择数据
xingxi1 = xingbie{v1}; % 确认获取的选择的数据
banji = get(handles.popupmenu2,'string'); % 获取第二个弹出框所选内容
v2 = get(handles.popupmenu2,'value');
xingxi2 = banji{v2};
c = {name,xingxi1,xingxi2}; % 把获取的数据放置在一起
set(handles.listbox1,'string',c); % 设置列表的输出项
function edit1_Callback(hObject, eventdata, handles)
% hObject handle to edit1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of edit1 as text
% str2double(get(hObject,'String')) returns contents of edit1 as a double
% --- Executes during object creation, after setting all properties.
function edit1_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit1 (see GCBO)% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'),
get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes on selection change in listbox1.
function listbox1_Callback(hObject, eventdata, handles)
% hObject handle to listbox1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = cellstr(get(hObject,'String')) returns listbox1 contents as
cell array
% contents{get(hObject,'Value')} returns selected item from listbox1
% --- Executes during object creation, after setting all properties.
function listbox1_CreateFcn(hObject, eventdata, handles)
% hObject handle to listbox1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: listbox controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'),
get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes on selection change in popupmenu1.
function popupmenu1_Callback(hObject, eventdata, handles)
% hObject handle to popupmenu1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = cellstr(get(hObject,'String')) returns popupmenu1 contents
as cell array
% contents{get(hObject,'Value')} returns selected item from popupmenu1
% --- Executes during object creation, after setting all properties.
function popupmenu1_CreateFcn(hObject, eventdata, handles)
% hObject handle to popupmenu1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: popupmenu controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'),
get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');end
% --- Executes on selection change in popupmenu2.
function popupmenu2_Callback(hObject, eventdata, handles)
% hObject handle to popupmenu2 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = cellstr(get(hObject,'String')) returns popupmenu2 contents
as cell array
% contents{get(hObject,'Value')} returns selected item from popupmenu2
% --- Executes during object creation, after setting all properties.
function popupmenu2_CreateFcn(hObject, eventdata, handles)
% hObject handle to popupmenu2 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: popupmenu controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'),
get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end

5-6-3、实现结果

5-7、实现屏幕绘图和改变屏幕颜色

5-7-1、GUI设计界面

第一章基础_标量_23

5-7-2、代码功能实现

function varargout = untitled3(varargin)
% UNTITLED3 MATLAB code for untitled3.fig
% UNTITLED3, by itself, creates a new UNTITLED3 or raises the existing
% singleton*.
%
% H = UNTITLED3 returns the handle to a new UNTITLED3 or the handle to
% the existing singleton*.
%
% UNTITLED3('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in UNTITLED3.M with the given input arguments.
%
% UNTITLED3('Property','Value',...) creates a new UNTITLED3 or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before untitled3_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to untitled3_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES
% Edit the above text to modify the response to help untitled3
% Last Modified by GUIDE v2.5 21-Sep-2023 15:29:32
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @untitled3_OpeningFcn, ...
'gui_OutputFcn', @untitled3_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
% --- Executes just before untitled3 is made visible.
function untitled3_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to untitled3 (see VARARGIN)
% Choose default command line output for untitled3
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
% UIWAIT makes untitled3 wait for user response (see UIRESUME)
% uiwait(handles.figure1);
% --- Outputs from this function are returned to the command line.
function varargout = untitled3_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get default command line output from handles structure
varargout{1} = handles.output;
% --- Executes on selection change in popupmenu1.
function popupmenu1_Callback(hObject, eventdata, handles)
% hObject handle to popupmenu1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = cellstr(get(hObject,'String')) returns popupmenu1 contents
as cell array
% contents{get(hObject,'Value')} returns selected item from popupmenu1
% --- Executes during object creation, after setting all properties.
function popupmenu1_CreateFcn(hObject, eventdata, handles)
% hObject handle to popupmenu1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: popupmenu controls usually have a white background on Windows.
% See ISPC and COMPUTER.if ispc && isequal(get(hObject,'BackgroundColor'),
get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes on button press in pushbutton1.
function pushbutton1_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --- Executes on button press in pushbutton2.
function pushbutton2_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton2 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
v=get(handles.popupmenu1,'value'); %获取选择数据
x= 0 : 0.01 : 2 * pi * v;
y=sin(x);
plot(handles.axes1,x,y); %在名为axes1的坐标轴中绘制一个图形
title('sin');
grid on;
% --------------------------------------------------------------------
function yellow_Callback(hObject, eventdata, handles)
% hObject handle to yellow (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
set(gcf,'color','y'); %改变屏幕背景颜色 当前为黄色
% --------------------------------------------------------------------
function green_Callback(hObject, eventdata, handles)
% hObject handle to green (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
set(gcf,'color','g'); %改变屏幕背景颜色 当前为黄色
% --------------------------------------------------------------------
function select_Callback(hObject, eventdata, handles)
% hObject handle to select (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)

5-7-3、实现结果

第一章基础_MATLAB_24

第六章、动态系统仿真

6-1、动态仿真过程

6-1-1、新建窗口

在命令行中输入 simulink 显示设计窗口

第一章基础_MATLAB_25

6-1-2、设计步骤

6-1-2-1、初始界面

选择 Blank Model 打开一个空白文件,使用时首先保存,选择保存的路径

第一章基础_标量_26

6-1-2-2、选择相应的节点

点击Library Browser按钮,打开选择界面,找到相应的节点

第一章基础_MATLAB_27

6-1-2-3、运行

点击运行按钮 Run ,相应的结果会出现在选择的输出节点上

第一章基础_表示图_28