基本操作
- a=10 工作区会出现运算结果ans
a=10; 后面加上 ; 则运算结果不会出现在 工作区
- Row vector : 行向量
A = [1 2 3 4]
Column vector 列向量
A = [1;2;3;4]
; 相当于 换行
- A = ( 1 21 6 5 17 9 31 2 7 ) A=\begin{pmatrix} 1 & 21 & 6 \\ 5 & 17 & 9 \\ 31 & 2 & 7 \end{pmatrix} A=⎝ ⎛153121172697⎠ ⎞ 从列开始计数,
1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
---|---|---|---|---|---|---|---|---|
1 | 5 | 31 | 21 | 17 | 2 | 6 | 9 | 7 |
A(8) = 9
A(1 3 5) = 1 31 17
A([1 3 ;1 3] ) =
(
1
31
1
31
)
\begin{pmatrix} 1 & 31 \\ 1 & 31 \end{pmatrix}
(113131)
A(2,3) = 9 (2行3列)
A([1 3],[1 3]) =
(
1
6
31
7
)
\begin{pmatrix} 1 & 6 \\ 31 & 7 \end{pmatrix}
(13167) (第一个[1 3] 是行,第二个[1 3] 是列,结果为它们的交集)
- A = ( 1 21 6 5 17 9 31 2 7 ) A = \begin{pmatrix} 1 & 21 & 6 \\ 5 & 17 & 9 \\ 31 & 2 & 7 \end{pmatrix} A=⎝ ⎛153121172697⎠ ⎞——> ( 1 76 6 5 17 9 31 0 7 ) \begin{pmatrix} 1 & 76 & 6 \\ 5 & 17 & 9 \\ 31 & 0 & 7 \end{pmatrix} ⎝ ⎛153176170697⎠ ⎞——> ( 1 0 0 5 0 0 31 0 7 ) \begin{pmatrix} 1 & 0 & 0 \\ 5 & 0 & 0 \\ 31 & 0 & 7 \end{pmatrix} ⎝ ⎛1531000007⎠ ⎞ ——> ( 1 0 0 5 0 0 ) \begin{pmatrix} 1 & 0 & 0 \\ 5 & 0 & 0 \end{pmatrix} (150000)
第一步: A(3,2)=0
第二步: A([1 2],[2 3])=[0 0;0 0]
第三步: A(3,:)=[]
- A = ( 1 2 3 4 ) A = \begin{pmatrix} 1 & 2 \\ 3 & 4 \end{pmatrix} A=(1324) , B = ( 9 9 9 9 ) B = \begin{pmatrix} 9 & 9 \\ 9 & 9 \end{pmatrix} B=(9999)
F
=
[
A
B
]
=
(
1
2
9
9
3
4
9
9
)
F = [A B] = \begin{pmatrix} 1 & 2 & 9 & 9 \\ 3 & 4 & 9 & 9 \end{pmatrix}
F=[AB]=(13249999) (增广矩阵)
G
=
[
A
∣
B
]
=
(
1
2
3
4
9
9
9
9
)
G = [A|B] = \begin{pmatrix} 1 & 2 \\ 3 & 4 \\ 9 & 9 \\ 9 & 9 \end{pmatrix}
G=[A∣B]=⎝
⎛13992499⎠
⎞
- A = ( 1 2 3 4 5 4 9 8 7 ) A = \begin{pmatrix} 1 & 2 & 3 \\ 4 & 5 & 4 \\ 9 & 8 & 7 \end{pmatrix} A=⎝ ⎛149258347⎠ ⎞, B = ( 3 3 3 2 4 9 1 3 1 ) B = \begin{pmatrix} 3 & 3 & 3 \\ 2 & 4 & 9 \\ 1 & 3 & 1 \end{pmatrix} B=⎝ ⎛321343391⎠ ⎞
(1) x1 = A + B
(2) x2 = A * B
(3) x3 = A. * B
A
.
∗
B
=
(
1
∗
3
2
∗
3
3
∗
3
4
∗
2
5
∗
4
4
∗
9
9
∗
1
8
∗
3
7
∗
1
)
A. * B = \begin{pmatrix} 1*3 & 2*3 & 3*3 \\ 4*2 & 5*4 & 4*9 \\ 9*1 & 8*3 & 7*1 \end{pmatrix}
A.∗B=⎝
⎛1∗34∗29∗12∗35∗48∗33∗34∗97∗1⎠
⎞ 有 . 则为element 之间
(4) x4 = A / B = A * inv(B) (B的逆矩阵)
(5) x5 = A. / B
A
.
/
B
=
(
1
/
3
2
/
3
3
/
3
4
/
2
5
/
4
4
/
9
9
/
1
8
/
3
7
/
1
)
A. /B = \begin{pmatrix} 1/3 & 2/3 & 3/3 \\ 4/2 & 5/4 & 4/9 \\ 9/1 & 8/3 & 7/1 \end{pmatrix}
A./B=⎝
⎛1/34/29/12/35/48/33/34/97/1⎠
⎞
(6) y1 = A + a
A
+
a
=
(
1
+
a
2
+
a
3
+
a
4
+
a
5
+
a
4
+
a
9
+
a
8
+
a
7
+
a
)
A + a = \begin{pmatrix} 1+a & 2+a & 3+a \\ 4+a & 5+a & 4+a \\ 9+a & 8+a & 7+a \end{pmatrix}
A+a=⎝
⎛1+a4+a9+a2+a5+a8+a3+a4+a7+a⎠
⎞
(7) y2 = A / a = A. /a
A
/
a
=
A
.
/
a
=
(
1
/
a
2
/
a
3
/
a
4
/
a
5
/
a
4
/
a
9
/
a
8
/
a
7
/
a
)
A /a = A./a = \begin{pmatrix} 1/a & 2/a & 3/a \\ 4/a & 5/a & 4/a \\ 9/a & 8/a & 7/a \end{pmatrix}
A/a=A./a=⎝
⎛1/a4/a9/a2/a5/a8/a3/a4/a7/a⎠
⎞
(8) y3 = A^a (a个A相乘)
(9) y4 = A.^a
A
.
a
=
(
1
a
2
a
3
a
4
a
5
a
4
a
9
a
8
a
7
a
)
A.^a = \begin{pmatrix} 1^a & 2^a & 3^a \\ 4^a & 5^a & 4^a \\ 9^a & 8^a & 7^a \end{pmatrix}
A.a=⎝
⎛1a4a9a2a5a8a3a4a7a⎠
⎞
** C = A’** (A的转置矩阵,绕着主对角线转一圈)
- eye(n) n*n identity spaced matrix n阶单位矩阵 ( 1 0 0 0 1 0 0 0 1 ) \begin{pmatrix} 1 & 0 & 0 \\ 0 & 1 & 0\\ 0 & 0 & 1 \end{pmatrix} ⎝ ⎛100010001⎠ ⎞
zeros(n1,n2) n1n2 zero matrix n1n2 阶0矩阵
ones(n1,n2) n1*n2 matrix with everyone entry as 1
diag() 对角矩阵
d
i
a
g
(
[
1
2
5
]
)
(
1
0
0
0
2
0
0
0
5
)
diag([1\ 2\ 5])\begin{pmatrix} 1 & 0 & 0 \\ 0 & 2 & 0\\ 0 & 0 & 5 \end{pmatrix}
diag([1 2 5])⎝
⎛100020005⎠
⎞ (只有对角线有element)
- Some Matrix related functions
A
=
(
1
2
3
0
5
6
7
0
9
)
A=\begin{pmatrix} 1 & 2 & 3 \\ 0 & 5 & 6 \\ 7 & 0 & 9 \end{pmatrix}
A=⎝
⎛107250369⎠
⎞
(1) max(A) =(7 5 9) (按照每一列column的最大值构成的行row)
(2) A的最大值 max(max(A))
(3) min(A) (按照每一列column的最小值构成的行row)
(4) min(min(A)) A 的最小值
(5) sum(A) (A的每一列column的和构成的行row)
(6) sum(sum(A)) A元素的和
(7) mean(A) (按照A每一列column的平均值构成的行row)
(8) mean(mean(A)) A 元素的平均值
(9) sort(A) (将A每一列column按照从小到大排序)
(10) sortrows(A) (将A的第一列column按照从小到大排序,对应的行row也应该随之改变)
(11) size(A) (A的行数row和列数column)
(12) length(A) (A的行数row和列数column的最大值)
(13) find(A==n) (A中元素n在第几个位置)
结构化程序和自定义函数
- 不等于 ** ~=**
- 1e100 这种表示法,被称为“科学计数法”。E 后的数表示10的多少次方。
1E100 = 1X 10的100次方
- variable = start : increment : end
- 在命令行窗口
clc 清屏
**clear value 将工作区的value值删掉 **
- Pre-allocating Space to Variables 为变量预分配空间
找到一个足够大的空间给向量A,
- tic 时间开始
toc 时间结束
tic
for ii = 1:2000
for jj = 1:2000
A(ii,jj)=ii+jj;
end
end
toc
//结果: 历时 1.863940 秒。
tic
A=zeros(2000,2000);
for ii = 1:size(A,1)
for jj = 1:size(A,2)
A(ii,jj) = ii+jj;
end
end
toc
// 结果: 历时 0.026470 秒。
因此,提前给矩阵A分配空间,matlab程序运行时间显著变短
- **size( ) **获取矩阵的行和列 A为矩阵
(1) s = size(A) 当只有一个输出参数时,返回一个行向量,该行向量的第一个元素是矩阵Matrix 的行数row,第二个元素是矩阵的列数column
(2) [row,column] = size(A);
当有两个输出参数时,size函数将矩阵matrix的行数返回给row,将矩阵的列数返回给column
(3) size(A,1); size返回行数row
size(A,2); size返回列数column
- 将一个矩阵复制到另一个矩阵
A = ( 0 − 1 4 9 − 14 25 − 34 49 64 ) A = \begin{pmatrix} 0 & -1 & 4 \\ 9 & -14 & 25\\ -34 & 49 & 64 \end{pmatrix} A=⎝ ⎛09−34−1−144942564⎠ ⎞
B = zeros(3); % 创建一个3*3的零矩阵B
A = [0,-1,4;9,-14,25;-34,49,64];
for i=1:3
for j=1:3
B(i,j)=A(i,j);
end
end
A =[0,-1,4;9,-14,25;-34,49,64];
[row, columns] = size(A); % row 为A矩阵的行, columns 为 A矩阵的列
B = zeros(row,columns); % 创建一个row*columns 的零矩阵
for i = 1:row
for j = 1:columns
B(i,j)=A(i,j); % 将 A矩阵的每一个元素分别赋值给矩阵B对应的元素
end
end
A =[0,-1,4;9,-14,25;-34,49,64];
sz = size(A); % sz 为行向量,元素分别为A的行与列
B = zeros(sz); % zeros 的参数为一个行向量
for i = 1:row
for j = 1:columns
B(i,j)=A(i,j);
end
end
- 如果矩阵A中的元素为负数,则矩阵B对应的元素改为10(续8)
% 如果矩阵A中的元素为负数,则矩阵B对应的元素改为10
A =[0,-1,4;9,-14,25;-34,49,64];
sz = size(A);
B = zeros(sz);
for i = 1:row
for j = 1:columns
if A(i,j)<0
B(i,j)=10;
else
B(i,j)=A(i,j);
end
end
end
- while 与 break
x = 2;
k = 0;
error = inf; % 无穷大常数
error_threshould = 1e-32; % 1*10^(-32)
while error > error_threshould
if k>100
break;
end
x = x - sin(x)/cos(x);
error = abs(x - pi); // 求整数的绝对值
k = k+1;
end
- clear all 移除工作区的所有变量
close all 关闭所有打开的图形
clc 清除命令行窗口的数据
语句后 加 ** ; ** 表示语句的结果不会显示在工作区,
A = [1,2,3,4,5,6;...
6,5,4,3,2,1];
使用 … 换行 ,防止一行过长
Ctrl+C 强制关闭程序
函数fumction
- ** edit(which(‘mean.h’));** 找到mean.m函数所在的位置
function x = freebody(x0,v0,t)
x= x0+v0.*t+1/2*9.8*t.*t; % 元素之间的点乘
% 在命令行窗口
% freebody([0 10],[0 10],[10 20])
% ans =
%
% 490 2170
function [a,F] = acc(v2,v1,t2,t1,m)
a = (v2-v1) ./(t2-t1);
F = m.* a;
% 在命令行窗口
% [Acc,Force]=acc(10,20,5,2,3)
% Acc = -3.3333 Force = -10
** * *两个数相乘
** . ** element之间的相乘
Chapter 02 课件
03Structured_Programming_&_Function.pdf
变量
s1 = 'Example';
s2 = ' String';
s3 = [s1 s2];
s4 = [s1; s2]; % s1 和 s2 的维度要一致
% 结果: s3 = 'Example String'
% s4= 'Example'
' String'
str = 'aardvark'; % index索引从1开始
'a'==str; % 'a'与str中的每一个字符比较,相同为1,不同为0
str(str=='a')='z'; % str(11000100) = z ; 第1,2,6个位置替换为z
strcmp(str,'aardvark'); % 比较两个字符串是否相同,相同返回1(true),否则返回0(false)
% 结果 ans=
% 1 1 0 0 0 1 0 0
% str = 'zzrdvzrk'
s1='I like the letter E';
len=strlength(s1); % 返回s1的长度
dlen = len;
j=1;
for i=dlen:-1:1
s2(j)=s1(i);
j=j+1;
end
student.name = 'John Doe';
student.id = 'jdo2@sfu.ca';
student.number = 301073268;
student.grade = [100,75,73; ...
95,91,85.5; ...
100,98,72];
student; % student被宣告为结构体
student(2).name = 'Ann Lane';
student(2).id = 'aln4@sfu.ca';
student(2).number = 301078853;
student(2).grade = [95,100,90; ...
95,82,97; ...
100,85,100];
% student =
%
% 包含以下字段的 1×2 struct 数组:
%
% name
% id
% number
% grade
% 在命令行窗口输入
% fieldnames(student) % 结构体的字段名
% 4×1 cell 数组
%
% {'name' }
% {'id' }
% {'number'}
% {'grade' }
% rmfield(student,'id') % 删除student结构体的id字段
% 结构体嵌套
A = struct('data',[3,4,7;8,0,1], ...
'nest', struct('testnum','Test 1','xdata',[4,2,8],'ydata',[7,1,6]));
A(2).data = [9,3,2;7,6,5];
A(2).nest.testnum = 'Test 2';
A(2).nest.xdata = [3,4,2];
A(2).nest.ydata = [5,0,9];
A.nest; % nest 是一个结构体
% data 的值就是 [3,4,7;8,0,1] ,
% nest 的值是 struct('testnum','Test 1','xdata',[4,2,8],'ydata',[7,1,6])
% 元胞数组 cell array
A(1,1)={[1,4,3;0,5,8;7,2,9]};
A(1,2) = {'Anne Smith'};
A(2,1) = {3+7i};
A(2,2) = {-pi:pi:pi};
A; % A被宣告为数组
% 元胞数组 cell array
A{1,1} = [1,4,3;0,5,8;7,2,9];
A{1,2} = 'Anne Smith';
A{2,1} = 3+7i;
A{2,2} = -pi:pi:pi;
A;
A(1,1) 是pointer 指向的内容
A{1,1} 是cell array 的内容
A{1,1} = [1,4,3;0,5,8;7,2,9];
A{1,2} = ‘Anne Smith’;
A{2,1} = 3+7i;
A{2,2} = [-pi 0 pi];
A;命令行:
A{1,1}(1)ans =
1
a = magic(3); % 1~ 9 的幻方矩阵
b = num2cell(a); % cell by cell
c = mat2cell(a,[1 1 1],3); % [1 1 1] row 行数 三行 3 3个column 在一起 1行5列
%%
% 2x2x2的 三维数组
A{1,1,1} = [1,2;4,5];
A{1,2,1} = 'Name';
A{2,1,1} = 2-4i;
A{2,2,1} = 7;
A{1,1,2} = 'Name2';
A{1,2,2} = 3;
A{2,1,2} = 0:1:3;
A{2,2,2} = [4 5];
%%
% 串联数组
A{1,1} = [1,2;4,5];
A{1,2} = 'Name ';
A{2,1} = 2-4i;
A{2,2} = 7;
B{1,1} = 'Name2';
B{1,2} = 0:1:3;
B{2,1} = 3;
B{2,2} = [4 5];
C = cat(3,A,B); %% 1 row 2 column 3 layer
% reshape 重构数组
A = {'James Bond',[1,2;3,4;5,6];pi,magic(5)};
C = reshape(A,1,4); % matrix C 为 one by four
%%
% 将work space 中的所有variable 存储在mydate1.mat中
a = magic(4);
save mydate1.mat -ascii % -ascii 通过notepad 打开时没有乱码
save mydate2.mat % 通过notepad 打开时有乱码
load('mydate2.mat'); % 将mydate2.mat 中的variable 存储在 work space
load ('mydate1.mat', '-ascii'); % 将mydate1.mat 中的variable 存储在 work space ,但是variable 名没有了,只有file 名 ,mydate1.mat 是以ascii文本模式加载的,所以要用 -ascii
% 只存储worksapce 中的某一个variable 时,
save mydate2.mat b -ascii
%%
% 将chapter 4.xlsx excel 文件中的数据读到 workspace
Score = xlsread('chapter 4.xlsx'); % 所有数据都读取
Score1 = xlsread('chapter 4.xlsx','B2:D4'); % 只读取 从B2到D4的数据
% 在命令行窗口:
M = mean(Score1')'; % mean 是column operation ,所以要转置matrix Score1,最后又恢复
xlswrite('chapter 4.xlsx',M,1,'E2:E4'); % 把平均数写入到chapter 4.xlsx excel 文件中
xlswrite('chapter 4.xlsx',{'Mean'},1,'E1'); % 将Mean 写入到E1为位置
% 标准差 std 是 column operation ,所以要转置matrix Score1,最后又恢复
% 在命令行窗口:
S = std(Score1')';
xlswrite('chapter 4.xlsx',S,1,'F2:F4'); % 把标准差写入到chapter 4.xlsx excel 文件中
xlswrite('chapter 4.xlsx',{'Std'},1,'F1'); % 将Std 写入到F1为位置
% 读取表头和数字
[Score Header] = xlsread('chapter 4.xlsx'); % Score: numeric variable 数字的, Header 为string
% Header 实际为 cell
%%
% 读写文件
x = 0: pi/10 : pi;
y = sin(x);
fid = fopen('sinx.txt','w'); % 打开文件
for i=1:10
fprintf(fid,'%5.3f %8.4f\n',x(i),y(i));
end
fclose(fid);
type sinx.txt % 查看sin.txt 文件内容
%%
% 读取文件,在命令行中
fid = fopen('04asciiData.txt','r');
i=1;
while ~feof(fid) % feof end of file 不到文件末尾返回0,反之返回1
name(i,:) = fscanf(fid,'%5c',1); % name(i,:)从column 第一个字符读到第三个字符 1 是size
year(i) = fscanf(fid,'%d',1);
no1(i) = fscanf(fid,'%d',1);
no2(i) = fscanf(fid,'%d',1);
no3(i) = fscanf(fid,'%g',1);
no4(i) = fscanf(fid,'%g\n',1);
i=i+1;
end
fclose(fid)
chapter 04 课件
04Data_Structure_&_File_Access.pdf
初阶绘图
hold on/off hold on 保留这个图在figure
hold on
plot(cos(0:pi/20:2*pi));
plot(sin(0:pi/20:2*pi));
hold off
hold on
plot(cos(0:pi/20:2*pi),'^-m');
plot(sin(0:pi/20:2*pi),'pr:');
hold off
x= 0:0.5:4*pi;
y = sin(x);
h = cos(x);
w = 1./(1+exp(-x));
g = (1/(2*pi*2)^0.5).*exp((-1.*(x-2*pi).^2)./(2*2^2));
plot(x,y,'bd-',x,h,'gp:',x,w,'ro-',x,g,'c^-');
legend('sin(x)','cos(x)','Sigmoid','Gauss function');
x = 0:0.1:2*pi;
y1 = sin(x);
y2 = exp(-x);
plot(x,y1,'--*',x,y2,':o');
xlabel('t = 0 to 2\pi');
ylabel('values of sin(t) and e^{-x}');
title('Function Plots of sin(t) and e^{-x}');
legend('sin(t)','e^{-x}');
% \pi --> Π e^{-x} 要用 {} 括起来
x = linspace(0,3);
y = x.^2.*sin(x);
plot(x,y,'-k');
line([2,2],[0,2^2*sin(2)]);
str = '$$ \int_{0}^{2} x^2\sin(x) dx $$';
text(0.25,2.5,str,'Interpreter','latex');
annotation('arrow','X',[0.32,0.5],'Y',[0.6,0.4]); % arrow 箭头
% linspace(x1,x2,N); 产生x1,x2之间的N点行向量,x1为起始值,x2为终止值,N为元素个数; linspace(x1,x2) N默认为100
% line([起点的横坐标,终点的横坐标],[起点的纵坐标,终点的纵坐标])
% '$$ $$' 是Latex的固定格式, \int 是积分号
% linspace() 返回的是row vector ,所以相乘的时候应该用 .*
’
’ 是Latex的固定格式, \int 是积分号
t = linspace(1,2);
f = t.*t;
g = sin(2*pi.*t);
plot(t,f,'k-',t,g,'or:');
xlabel('Time(ms)');
ylabel('f(t)');
title('Mini Assignment #1');
legend('t^{2}','sin(2\pit)');
x = linspace(0,2*pi,1000);
y = sin(x);
h = plot(x,y);
get(h);
% h 是 handle of sin(x) line
% axes 轴(x轴,y轴)
% gca is handle of axes
Line Properties(属性)
AlignVertexCenters: off
Annotation: [1×1 matlab.graphics.eventdata.Annotation]
BeingDeleted: off
BusyAction: ‘queue’
ButtonDownFcn: ‘’
Children: [0×0 GraphicsPlaceholder]
Clipping: on
Color: [0 0.4470 0.7410]
ColorMode: ‘auto’
ContextMenu: [0×0 GraphicsPlaceholder]
CreateFcn: ‘’
DataTipTemplate: [1×1 matlab.graphics.datatip.DataTipTemplate]
DeleteFcn: ‘’
DisplayName: ‘’
HandleVisibility: ‘on’
HitTest: on
Interruptible: on
LineJoin: ‘round’
LineStyle: ‘-’
LineStyleMode: ‘auto’
LineWidth: 0.5000
Marker: ‘none’
MarkerEdgeColor: ‘auto’
MarkerFaceColor: ‘none’
MarkerIndices: [1×1000 uint64]
MarkerMode: ‘auto’
MarkerSize: 6
Parent: [1×1 Axes]
PickableParts: ‘visible’
Selected: off
SelectionHighlight: on
SeriesIndex: 1
Tag: ‘’
Type: ‘line’
UserData: []
Visible: on
XData: [1×1000 double]
XDataMode: ‘manual’
XDataSource: ‘’
YData: [1×1000 double]
YDataSource: ‘’
ZData: [1×0 double]
ZDataSource: ‘’
Axes(轴) properties
**commond: get(gca) **
ALim: [0 1]
ALimMode: ‘auto’
AlphaScale: ‘linear’
Alphamap: [1×64 double]
AmbientLightColor: [1 1 1]
BeingDeleted: off
Box: on
BoxStyle: ‘back’
BusyAction: ‘queue’
ButtonDownFcn: ‘’
CLim: [0 1]
CLimMode: ‘auto’
CameraPosition: [3.5000 0 17.3205]
CameraPositionMode: ‘auto’
CameraTarget: [3.5000 0 0]
CameraTargetMode: ‘auto’
CameraUpVector: [0 1 0]
CameraUpVectorMode: ‘auto’
CameraViewAngle: 6.6086
CameraViewAngleMode: ‘auto’
Children: [1×1 Line]
Clipping: on
ClippingStyle: ‘3dbox’
Color: [1 1 1]
ColorOrder: [7×3 double]
ColorOrderIndex: 2
ColorScale: ‘linear’
Colormap: [256×3 double]
ContextMenu: [0×0 GraphicsPlaceholder]
CreateFcn: ‘’
CurrentPoint: [2×3 double]
DataAspectRatio: [3.5000 1 1]
DataAspectRatioMode: ‘auto’
DeleteFcn: ‘’
FontAngle: ‘normal’
FontName: ‘Helvetica’
FontSize: 10
FontSizeMode: ‘auto’
FontSmoothing: on
FontUnits: ‘points’
FontWeight: ‘normal’
GridAlpha: 0.1500
GridAlphaMode: ‘auto’
GridColor: [0.1500 0.1500 0.1500]
GridColorMode: ‘auto’
GridLineStyle: ‘-’
HandleVisibility: ‘on’
HitTest: on
InnerPosition: [0.1300 0.1100 0.7750 0.8150]
Interactions: [1×1 matlab.graphics.interaction.interface.DefaultAxesInteractionSet]
Interruptible: on
LabelFontSizeMultiplier: 1.1000
Layer: ‘bottom’
Layout: [0×0 matlab.ui.layout.LayoutOptions]
Legend: [0×0 GraphicsPlaceholder]
LineStyleOrder: ‘-’
LineStyleOrderIndex: 1
LineWidth: 0.5000
MinorGridAlpha: 0.2500
MinorGridAlphaMode: ‘auto’
MinorGridColor: [0.1000 0.1000 0.1000]
MinorGridColorMode: ‘auto’
MinorGridLineStyle: ‘:’
NextPlot: ‘replace’
NextSeriesIndex: 2
OuterPosition: [0 0 1 1]
Parent: [1×1 Figure]
PickableParts: ‘visible’
PlotBoxAspectRatio: [1 0.7882 0.7882]
PlotBoxAspectRatioMode: ‘auto’
Position: [0.1300 0.1100 0.7750 0.8150]
PositionConstraint: ‘outerposition’
Projection: ‘orthographic’
Selected: off
SelectionHighlight: on
SortMethod: ‘childorder’
Subtitle: [1×1 Text]
SubtitleFontWeight: ‘normal’
Tag: ‘’
TickDir: ‘in’
TickDirMode: ‘auto’
TickLabelInterpreter: ‘tex’
TickLength: [0.0100 0.0250]
TightInset: [0.0510 0.0527 0.0071 0.0200]
Title: [1×1 Text]
TitleFontSizeMultiplier: 1.1000
TitleFontWeight: ‘normal’
TitleHorizontalAlignment: ‘center’
Toolbar: [1×1 AxesToolbar]
Type: ‘axes’
Units: ‘normalized’
UserData: []
View: [0 90]
Visible: on
XAxis: [1×1 NumericRuler]
XAxisLocation: ‘bottom’
XColor: [0.1500 0.1500 0.1500]
XColorMode: ‘auto’
XDir: ‘normal’
XGrid: off
XLabel: [1×1 Text]
XLim: [0 7]
XLimMode: ‘auto’
XMinorGrid: off
XMinorTick: off
XScale: ‘linear’
XTick: [0 1 2 3 4 5 6 7]
XTickLabel: {8×1 cell}
XTickLabelMode: ‘auto’
XTickLabelRotation: 0
XTickMode: ‘auto’
YAxis: [1×1 NumericRuler]
YAxisLocation: ‘left’
YColor: [0.1500 0.1500 0.1500]
YColorMode: ‘auto’
YDir: ‘normal’
YGrid: off
YLabel: [1×1 Text]
YLim: [-1 1]
YLimMode: ‘auto’
YMinorGrid: off
YMinorTick: off
YScale: ‘linear’
YTick: [-1 -0.8000 -0.6000 -0.4000 -0.2000 0 0.2000 0.4000 0.6000 0.8000 1]
YTickLabel: {11×1 cell}
YTickLabelMode: ‘auto’
YTickLabelRotation: 0
YTickMode: ‘auto’
ZAxis: [1×1 NumericRuler]
ZColor: [0.1500 0.1500 0.1500]
ZColorMode: ‘auto’
ZDir: ‘normal’
ZGrid: off
ZLabel: [1×1 Text]
ZLim: [-1 1]
ZLimMode: ‘auto’
ZMinorGrid: off
ZMinorTick: off
ZScale: ‘linear’
ZTick: [-1 0 1]
ZTickLabel: ‘’
ZTickLabelMode: ‘auto’
ZTickLabelRotation: 0
ZTickMode: ‘auto’
**6~7之间有空白,现在要求 X_Axes limits 为 [0,2Π], Y_Axes Limits 为[-1,1] **
用 axes limits 不用 line limit
set(gca,‘XLim’,[0,2*pi]);
set(gca,‘YLim’,[-1,1]); % gca is axes handle
x = linspace(0,2*pi,1000);
y = sin(x);
h = plot(x,y);
get(h);
set(gca,'XLim',[0,2*pi]);
set(gca,'YLim',[-1.2,1.2]);
ylim([-1,1]);
把Font(字体)变为symbol(符号)后,就可以将0,90°,180°变为0,Π/2,Π ,symbol中 p就是Π,
现有一个问题,执行 set(gca,‘FontName’,‘symbol’); 后,axes上的字体变成了方块,
方法一:不执行 set(gca,‘FontName’,‘symbol’); ,直接执行 set(gca,‘XTickLabel’,{‘0’,‘\pi/2’,‘\pi’,‘3\pi/2’,‘2\pi’});
x = linspace(0,2*pi,1000);
y = sin(x);
h = plot(x,y);
get(h);
set(gca,'XLim',[0,2*pi]);
set(gca,'YLim',[-1.2,1.2]);
ylim([-1,1]);
set(gca,'FontSize',25);
set(gca,'XTick',0:pi/2:2*pi);
set(gca,'XTickLabel',0:90:360);
%set(gca,'FontName','symbol');
set(gca,'XTickLabel',{'0','\pi/2','\pi','3\pi/2','2\pi'});
% set(gca,'XLim',[0,2*pi]); --> xlim([0,2*pi]);
% set(gca,'YLim',[-1.2,1.2]); --> ylim([-1.2,1.2]);
set(h,'LineStyle','-.',...
'LineWidth',7.0,'Color','g');
% 或者 plot(x,y,'-.g',...
'LineWidth',7.0);
% delete(h); 删除了图像h,axes还在
A = rand(20,1); % 返回20*1的随机矩阵, returns an 20 by 1 array of random numbers
set(gca,'FontSize',18);
plot(A,'-md','LineWidth',2,'MarkerEdgeColor','k',...
'MarkerFaceColor','g','MarkerSize',10);
set(gca,'XLim',[1,20]);
% plot(y); ( y =sin(x)), 默认 x=[0,1,2,3...n] ;
% plot(x,y) x 的范围在前面已被限定
hold on
t = linspace(1,2); % 默认有100个数
y1 = t.*t;
y2 = sin(2*pi.*t);
plot(t,y1,'-k','LineWidth',5);
plot(t,y2,'or','MarkerEdgeColor','m','MarkerFaceColor','b');
xlabel('Time(ms)');
ylabel('f(t)');
title('Mini Assignment #1');
legend('t^{2}','sin({2\pit})');
set(gca,'XTick',1:0.2:2);
set(gca,'YTick',-1:1:4);
set(gca,'FontSize',15)
hold off
multiple figure
当画第二张图的时候,handle point to current figure/axes
x = -10:0.1:10; % x is vector
y1 = x.^2-8; % x的每个元素做运算,做点乘
y2 = exp(x);
figure,plot(x,y1);
figure,plot(x,y2);
% 呼叫两个figure,做两张图
一张图中多张子图
subplot(m,n,1); m个行,n个列
t = 0:0.1:2*pi;
x = 3*cos(t);
y = sin(t);
subplot(2,2,1); plot(x,y); axis normal
subplot(2,2,2); plot(x,y); axis square
subplot(2,2,3); plot(x,y); axis equal
subplot(2,2,4); plot(x,y); axis equal tight
:::warning
axis off 只能操作current axes ,关闭最后一张子图的axes
box 是x轴上方,y轴上方
操作时只能操作最后一张子图
axis (复数 axes) 轴
:::
:::success
equal 是 x轴的unit == y轴的unit , square 是 x轴的总长度==y轴的总长度
equal tight 是画的line 与 axes 相切
图形的横纵坐标范围不变,只是改变了坐标轴上的分度值
:::
chapter 05 课件
进阶绘图
Logarithm plot 对数图
x = logspace(-1,1,100); x = 10^-1 … 10^1 ,一共100个数 (默认是50个数)
x = logspace(-1,1,100); % x is vector ,运算时点乘 .* , x = 10^-1 ~ 10^1 ,一共100个数
y = x.^2;
subplot(2,2,1); plot(x,y); title('Plot');
subplot(2,2,2); semilogx(x,y); title('Semilogx'); % semi 一半, 对x轴取对数,y轴不变
subplot(2,2,3); semilogy(x,y); title('Semilogy'); % semi 一半, 对y轴取对数,x轴不变
subplot(2,2,4); loglog(x,y); title('LogLog'); % 对x,y轴取对数
set(gca,'XGrid','on');
只有最后一张子图有网格,因为current handle --> 最后一张 figure ,所以只能操作最后一张图
对数 图的网格差很大
问题: 2020b版本 plotyy 不建议用, 改为 yyaxis
yyaxis left; plot(x,y1);
yyaxis right; plot(x,y2);
x = 0:0.01:20;
y1 = 200*exp(-0.05*x).*sin(x);
y2 = 0.8*exp(-0.5*x).*sin(10*x);
yyaxis left ;
plot(x,y1,'LineStyle','-');
ylabel('Left Y-axis');
yyaxis right ;
plot(x,y2,'LineStyle',':'); ylabel('Right Y-axis');
title('Labeling yyaxis');
y = randn(1,1000);
subplot(2,1,1); hist(y,10);
title('Bins = 10');
subplot(2,1,2); hist(y,50);
title('Bins = 50');
randn(n,m); 返回一个n*m的矩阵
histogram 将 bin 显示为矩形,这样每个矩形的高度就表示 bin 中的元素数量。
y = randn(1,1000);
subplot(2,1,1); histogram(y,10); title('Bins = 10');
subplot(2,1,2); histogram(y,50); title('Bins = 50');
x = [1 2 5 7 8];
y = [x;1:5];
subplot(1,3,1); bar(x); title('A bargraph of vector x');
subplot(1,3,2); bar(y); title('A bargraph of vector y');
subplot(1,3,3); bar3(y); title('A 3D bargraph'); % bar3 3D图 ,三个维度分别是 bar,group,value
x = [1 2 5 7 8];
y = [x;1:5];
subplot(1,2,1); bar(y,'stacked'); title('Stacked');
subplot(1,2,2); barh(y); title('Horizontal'); // 水平图
% stacked 将每个group的数据加和,更直观
x = [1 2 5 7 8];
y = [x;1:5];
subplot(1,2,1); bar(y,'stacked'); title('Stacked');
subplot(1,2,2); barh(y,'stacked'); title('Horizontal'); % barh 后再加一个参数 stacked
a = [10 5 20 30];
subplot(1,3,1); pie(a);
subplot(1,3,2); pie(a,[0 0 0 1]);
subplot(1,3,3); pie3(a,[0 0 0 1]);
pie(a,[0 0 0 1]); 中的[0 0 0 1] 分别对应a中的每个元素, 为0,则说明连接在一起, 为1(不为0,就裂开) 说明 裂开
pie3 立体图
a = [10 5 20 30];
subplot(1,3,1); pie(a);
subplot(1,3,2); pie(a,[1 1 1 1]);
subplot(1,3,3); pie3(a,[1 1 1 1]);
x= 1:100; theta = x/10; r = log10(x);
subplot(1,4,1); polarplot(theta,r);
theta = linspace(0,2*pi); r = cos(4*theta);
subplot(1,4,2); polarplot(theta,r);
theta = linspace(0,2*pi,6); g = length(theta); r = ones(1,length(theta));
subplot(1,4,3); polarplot(theta,r);
theta = linspace(0,2*pi); r = 1-sin(theta);
subplot(1,4,4); polarplot(theta,r);
polarplot include theta and r
五边形: linspace(0,2pi,6) 0到2Π ,一共6个点,分成了5份,起始点和终止点重合
或 **theta = 0:2/5pi:2*pi**
theta = linspace(0,2*pi,7); g = length(theta); r = ones(1,length(theta));
subplot(1,4,3); polarplot(theta,r);
x = linspace(0,4*pi,40);
y = sin(x);
subplot(1,2,1); stairs(y);
subplot(1,2,2); stem(y);
** stairs ** ** stem**
hold on
t = linspace(0,10,230);
y=sin((pi*t.^2)/4);
plot(t,y,'b');
stem(t,y,'r');
set(gca,'YTick',-1:0.5:1);
set(gca,'XTick',0:1:10);
title('f(t)=sin(\pit^{2}/4)');
xlabel('t');
ylabel('f(t)');
hold off
plot(y); x轴就是自变量x的length
load carsmall
boxplot(MPG,Origin);
x = 0:pi/10:pi; y = sin(x);
e = std(y)*ones(size(x));
errorbar(x,y,e);
% size 返回vector 的维度的长度
% errorbar 误差线
% std 返回matrix 列的标准差组成vector
% ones(n,m) 返回n*m 的matrix
t = (1:2:15)'*pi/8;
x = sin(t); y = cos(t);
fill(x,y,'r');
axis square off; % 关闭axis 的框
text(0,0,'STOP','Color','w','FontSize',80,...
'FontWeight','bold','HorizontalAlignment','center');
t = 0:pi/2:2*pi;
x =sin(t); y = cos(t);
fill(x,y,'y');
axis square off;
text(0,0,'WAIT','Color','k','FontSize',70,...
'FontWeight','bold','HorizontalAlignment','center');
G= [46 38 29 24 13];
S = [29 27 17 26 8];
B = [29 23 19 32 7];
h = bar(1:5,[G',S',B']);
title('Media count for top 5 countries in 2012 Olympics');
ylabel('Number of medals');
xlabel('Country');
legend('Gold','Silver','Bronze');
set(gca,'XTicklabel',{'USA','CHN','GBR','RUS','KOR'});
h(1).FaceColor='#CCCC00';
h(2).FaceColor='#666699';
h(3).FaceColor='#996600';
[x, y]=meshgrid(-3:.2:3,-3:.2:3);
z = x.^2+x.*y+y.^2;
surf(x,y,z);
box on;
set(gca,'FontSize',16,'XLim',[-4 4],'YLim',[-4 4]);
zlabel('z'); xlabel('x'); ylabel('y');
imagesc(z); axis square; xlabel('x'); ylabel('y');
[x, y] = meshgrid(-3:.2:3,-3:.2:3);
z = x.^2 + x.*y + y.^2; surf( x, y, z); box on;
set(gca,'FontSize', 16); zlabel('z');
xlim([-4 4]); xlabel('x'); ylim([-4 4]); ylabel('y');
imagesc(z); axis square; xlabel('x'); ylabel('y');
(1)[x,y]=meshgrid(-3:.2:3, -3:.2:3); 基于向量 x 和 y 中包含的坐标返回二维网格坐标。X 是一个矩阵,每一行是 x 的一个副本;Y 也是一个矩阵,每一列是 y 的一个副本。坐标 X 和 Y 表示的网格有 length(y) 个行和 length(x) 个列。.2 代表0.2密度的意思
(2)surf(x,y,z); 创建一个三维曲面图,它是一个具有实色边和实色面的三维曲面。该函数将矩阵 Z 中的值绘制为由 X 和 Y 定义的 x-y 平面中的网格上方的高度。曲面的颜色根据 Z 指定的高度而变化。曲面图对高度和颜色均使用z
**surf(x,y,z,c); **C 表示颜色。使用_颜色图_指定颜色,该颜色图使用单个数字表示色谱上的颜色。使用颜色图时,C 与 Z 大小相同。
**(3)imagesc(z); 这里的z就是颜色c, **将数组 C 中的数据显示为一个图像,该图像使用颜色图中的全部颜色。C 的每个元素指定图像的一个像素的颜色。生成的图像是一个 m×n 像素网格,其中 m 和 n 分别是 C中的行数和列数。这些元素的行索引和列索引确定了对应像素的中心。
colorbar; % 色阶的颜色栏
x = [1:10;3:12;5:14];
imagesc(x);
colorbar;
map = zeros(256,3);
map(:,2)=(0:255)/255;
colormap(map);
map(:,2)=(0:255)/255;
map(: , 2) ; : 表示所有行 2 表示第二列
colormap() 返回的是一个256*3的矩阵, 矩阵中的每个元素范围在 0~1 之间
颜色可以看作是另一个维度
x = 0:0.1:3*pi;
z1 = sin(x); z2 = sin(2.*x); z3 = sin(3.*x);
y1 = zeros(size(x)); y3 = ones(size(x)); y2 = y3./2;
plot3(x,y1,z1,'r',x,y2,z2,'b',x,y3,z3,'g');
xlabel('x-axis');
ylabel('y-axis');
zlabel('z-axis');
title('plot3D');
grid on;
turns = 40*pi;
t = linspace(0,turns,400);
x = cos(t).*(turns-t)./turns;
y = sin(t).*(turns-t)./turns;
z = t./turns;
plot3(x,y,z); grid on;
x = -2:1:2; y = -2:1:2;
[X,Y] = meshgrid(x,y)
命令行窗口:
X =
-2 -1 0 1 2
-2 -1 0 1 2
-2 -1 0 1 2
-2 -1 0 1 2
-2 -1 0 1 2
Y =
-2 -2 -2 -2 -2
-1 -1 -1 -1 -1
0 0 0 0 0
1 1 1 1 1
2 2 2 2 2
x = -3.5:0.2:3.5; y = -3.5:0.2:3.5;
[X,Y] = meshgrid(x,y);
Z = X.*exp(-X.^2-Y.^2);
%subplot(1,2,1); mesh(X,Y,Z);
%subplot(1,2,2); surf(X,Y,Z);
figure, mesh(X,Y,Z);
figure,surf(X,Y,Z);
mesh() (mesh网格) surf() 给网格填充颜色了
x = -3.5:0.2:3.5; y = -3.5:0.2:3.5;
[X,Y] = meshgrid(x,y); Z = X.*exp(-X.^2-Y.^2);
subplot(1,3,1); contour(Z,[-.45:.05:.45]); axis square;
subplot(1,3,2); [C,h]=contour(Z); clabel(C,h); axis square;
subplot(1,3,3); contourf(Z); axis square;
hold on
x = -3.5:0.2:3.5; y = -3.5:0.2:3.5;
[X,Y]=meshgrid(x,y); Z = X.*exp(-X.^2-Y.^2);
[C,h]=contourf(Z,(-0.45:0.05:0.45)); clabel(C,h);
axis square;
hold off;
(1)[X,Y]=meshgrad(x,y); 基于向量x,y中包含的坐标返回二维网络坐标,
X是一个矩阵,row是x的一个副本;
Y是一个矩阵,column是y的一个副本;
(2)**.45 **–> 0.45
(3)[C,h]=contour(Z); 返回等高矩阵M,等高线对象h,显示等高线图后,使用h来设置属性
(4)clabel(C,h); 为当前等高线图添加标签,将旋转文本插入每条等高线。
x = -3.5:0.2:3.5; y = -3.5:0.2:3.5;
[X,Y]=meshgrid(x,y); Z = X.*exp(-X.^2-Y.^2);
subplot(1,2,1); meshc(X,Y,Z);
subplot(1,2,2); surfc(X,Y,Z);
sphere(50); shading flat;
light('Position',[1 3 2]);
light('Position',[-3 -1 3]);
material shiny;
axis vis3d off;
set(gcf,'Color','#FFFFFF');
colormap(jet);
%set(gcf,'Color',[1 1 1]);
view(-45,20);
[X,Y,Z]=sphere(64); h = surf(X,Y,Z);
axis square vis3d off;
reds = zeros(256,3); red(:,3) = (0:256.-1)/255;
colormap(reds); shading interp; lighting phong;
set(h,'AmbientStrength',0.75,'DiffuseStrength',0.5);
L1 = light('Position',[-1,-1,-1]);
colormap(jet);
v = [0 0 0; 1 0 0 ; 1 1 0; 0 1 0; 0.25 0.25 1; ...
0.75 0.25 1; 0.75 0.75 1; 0.25 0.75 1];
f = [1 2 3 4; 5 6 7 8; 1 2 6 5; 2 3 7 6; 3 4 8 7; 4 1 5 8];
subplot(1,2,1); patch('Vertices', v, 'Faces', f, ...
'FaceVertexCData', hsv(6), 'FaceColor', 'flat');
view(3); axis square tight; grid on;
subplot(1,2,2); patch('Vertices', v, 'Faces', f, ...
'FaceVertexCData', hsv(8), 'FaceColor', 'interp');
view(3); axis square tight; grid on;
load cape
X=conv2(ones(9,9)/81,cumsum(cumsum(randn(100,100)),2));
surf(X,'EdgeColor','none','EdgeLighting','Phong',...
'FaceColor','interp');
colormap(map); caxis([-10,300]);
grid off; axis off;
chapter 06 课件
微积分
多项式的微积分
%%
% 多项式
a = [9,-5,3,7]; % 多项式的系数(指数由大到小排序3 2 1 0)
x = -2:0.01:5; % x 轴
f = polyval(a,x); % 算多项式 p(最小项指数为0) 在 x 的每个点处的值
plot(x,f,'LineWidth',2,'Color','r');% x 为横坐标 y 为纵坐标 LineWidth 为图像的线粗度 =2
xlabel('x'); % 为 x 轴添加标签
ylabel('f(x)'); % 为 y 轴添加标签
set(gca,'FontSize',14);
%%
% 多项式的微分
p = [5 0 -2 0 1]; % 多项式 5x^4 - 2x^2 +1
polyder(p) % diff 微分 polynomial 多项式 即 20x^3 - 4x
polyval(polyder(p),7) % 微分多项式在7的值f'(7)
%%
% conv 卷积和多项式乘法 对两个多项式乘积
a = [5 -7 5 10];
b = [4 12 -3];
c = conv(a,b) % conv 卷积和多项式乘法
c
=
(
5
X
3
−
7
X
2
+
5
X
+
10
)
(
4
X
2
+
12
X
−
3
)
c = (5X^3-7X^2+5X+10)(4X^2+12X-3)
c=(5X3−7X2+5X+10)(4X2+12X−3)
表示虚数 2+4i --> 2+i*4
hold on
c = [5,-7,5,10]; d = [4,12,-3];
e = conv(a,d); x1 = -2:0.1:1;
f0 = polyval(e,x1);
f1 = polyval(polyder(e),x1);
plot(x1,f0,'--b');
plot(x1,f1,'r-');
legend('f(x)',"f'(x)");
hold off
p = [5,0,-2,0,1];
f = polyint(p,3) % 加的常数是3
polyval(f,7)
f
=
(
1.0000
0
−
0.6667
0
1.0000
3.0000
)
f=\begin{pmatrix} 1.0000 & 0 & -0.6667 & 0 & 1.0000 & 3.0000 \end{pmatrix}
f=(1.00000−0.666701.00003.0000) 积分后的多项式的系数
数值的微积分
数值的微分
x = [1,2,5,2,1]; % 五个元素,前后的差异有四个
diff(x)
% ans = [ 1 3 -3 -1]
x = [1,2]; y = [5,7];
slope = diff(y)./diff(x) % 斜率
% ans =2
x0 = pi/2; h = 0.1;
x = [x0,x0+h];
y = [sin(x0),sin(x0+h)];
slope = diff(y)./diff(x)
h | Error of f’(x) (误差) |
---|---|
0.1 | -0.0500 |
0.01 | -0.0050 |
0.001 | -5.0000e-04 |
0.0001 | -5.0000e-05 |
0.00001 | -5.0000e-06 |
0.000001 | -5.0004e-07 |
0.0000001 | -4.9960e-08 |
0.00000001 | 0 |
hold on
h = 0.000001;
x = 0:h:2*pi;
x1 = 0:h:2*pi-h; %
y = sin(x);
m = diff(y)./diff(x);
plot(x,y,'-r');
plot(x1,m,'--b');
legend("sin(x)","sin'(x)");
hold off
g = colormap(lines);
hold on;
for i = 1:4
x = 0:power(10,-i):pi;
y = sin(x);
m = diff(y)./diff(x);
%x1 = 0:power(10,-i):pi-power(10,-i);
plot(x(1:end-1),m,'Color',g(i,:));
%plot(x1(1:end),m,'Color',g(i,:));
end
hold off;
set(gca,'XLim',[0,pi/2]);
set(gca,'YLim',[0,1.2]);
set(gca,'FontSize',18);
set(gca,'XTick',0:pi/4:pi/2);
set(gca,'XTickLabel',{'0','\pi/4','\pi/2'});
legend('h=0.1','h=0.01','h=0.001','h=0.0001');
g = colormap(lines);
hold on;
for i = 1:3
x = 0:power(10,-i):2*pi;
y =exp(-x).*sin(x.*x/2);
m = diff(y)./diff(x);
%x1 = 0:power(10,-i):pi-power(10,-i);
plot(x(1:end-1),m,'Color',g(i,:));
%plot(x1(1:end),m,'Color',g(i,:));
end
hold off;
set(gca,'XLim',[0,pi*2]);
set(gca,'YLim',[0,0.2]);
set(gca,'FontSize',18);
set(gca,'XTick',0:pi/2:pi*2);
set(gca,'XTickLabel',{'0','\pi/2','\pi','3\pi/2','2\pi'});
legend('h=0.1','h=0.01','h=0.001');
x = -2 : 0.005 : 2; y = x.^3;
m = diff(y)./diff(x); % y'
m2 = diff(m)./diff(x(1:end-1)); % y'' ,diff()是差值,m比x 少一,所以x减一(即最后一个数删去),保持维度一样、
plot(x,y,x(1:end-1),m,x(1:end-2),m2);
xlabel('x','FontSize',18);
ylabel('y','FontSize',18);
legend('f(x)=x^3',"f'(x)","f''(x)");
set(gca,'FontSize',18);
数值的积分
Basic quadrature rules 基本正交规则
Midpoint rule(zeroth-order approximation) 中点规则(零阶近似)
Trapezoid rule(first-order approximation) 梯形法则(一阶近似)
Midpoint rule(zeroth-order approximation) 中点规则(零阶近似)
h = 0.05; x = 0:h:2;
midpoint = (x(1:end-1)+x(2:end))./2;
y = 4*midpoint.^3; % y是矩形的高
s = sum(h.*y)
:::success
s =15.9950
:::
h = 0.0005; x = 0:h:2;
midpoint = (x(1:end-1)+x(2:end))./2;
y = 4*midpoint.^3; % y是矩形的高
s = sum(h.*y)
:::success
s =16.0000
:::
Trapezoid rule(first-order approximation) 梯形法则(一阶近似)
h = 0.05;
x = 0:h:2;
y = 4*x.^3;
s = trapz(y)*h
:::success
s = 16.0100
:::
trapz(y) —>
f
(
x
1
)
+
f
(
x
2
)
2
\frac{f\left(x_{1}\right)+f\left(x_{2}\right)}{2}
2f(x1)+f(x2)
h = 0.001; x = 0:h:2; y = 4*x.^3;
trapezoid = (y(1:end-1)+y(2:end))/2;
s = h*sum(trapezoid)
辛普森积分(simpson)(二阶逼近)
∫
a
b
f
(
x
)
d
x
≈
b
−
a
6
n
[
y
0
+
y
2
n
+
4
(
y
1
+
y
3
+
⋯
+
y
2
n
−
1
)
+
2
(
y
2
+
y
4
+
⋯
+
y
2
n
−
2
)
]
\int_{a}^{b} f(x) d x \approx \frac{b-a}{6 n}\left[y_{0}+y_{2 n}+4\left(y_{1}+y_{3}+\cdots+y_{2 n-1}\right)+2\left(y_{2}+y_{4}+\cdots+y_{2 n-2}\right)\right]
∫abf(x)dx≈6nb−a[y0+y2n+4(y1+y3+⋯+y2n−1)+2(y2+y4+⋯+y2n−2)]
h = 0.05; x = 0:h:2; y = 4*x.^3;
n2 = 2/0.05; n = n2/2;
s = 2/(6*n) * (y(1)+y(end)+4*sum(y(2:2:end-1))+2*sum(y(3:2:end-2)))
:::success
s = 16
:::
h = 0.05; x = 0:h:2; y = 4*x.^3;
s = h/3*(y(1)+2*sum(y(3:2:end-2))+...
4*sum(y(2:2:end))+y(end))
matlab中数组小标从1开始
4sum(y(2:2:end)) 与 4sum(y(2:2:end-1)) 它只能到第(end-1)个数,所以两个相同
h/3 == (b-a)/(6*n)
3
function handle(@) 函数指针
一个函数的输入参数应该是另一个函数的指针@,而不能是这个函数本身
function [y] = xy_plot(input,x)
% xy_plot receives the handle of a function
% and plots that function of x
y = input(x); plot(x,y,'r--');
xlabel('x'); ylabel('function(x)');
end
subplot(1,3,1); xy_plot(@sin,0:0.01:2*pi);
subplot(1,3,2); xy_plot(@cos,0:0.01:2*pi);
subplot(1,3,3); xy_plot(@exp,0:0.01:2*pi);
数值积分 numercial intergration
一重积分 integral
∫
0
2
1
x
3
−
2
x
−
5
d
x
\int_{0}^{2} \frac{1}{x^{3}-2 x-5} d x
∫02x3−2x−51dx
y = @ (x) 1./(x.^3-2*x-5);
integral(y,0,2)
y是function handle
:::success
y=-0.4605
:::
二重积分 integral2
f = @ (x,y) y.*sin(x)+x.*cos(x); % f是function handle
integral2(f,pi,2*pi,0,pi)
:::success
ans = -3.5864
:::
三重积分 integral3
f ( x , y ) = ∫ − 1 1 ∫ 0 1 ∫ 0 π ( y ⋅ sin ( x ) + z ⋅ cos ( y ) ) d x d y d z f(x, y)=\int_{-1}^{1} \int_{0}^{1} \int_{0}^{\pi}(y \cdot \sin (x)+z \cdot \cos (y)) d x d y d z f(x,y)=∫−11∫01∫0π(y⋅sin(x)+z⋅cos(y))dxdydz
f = @(x,y,z) y.*sin(x)+z.*cos(y);
integral3(f,0,pi,0,1,-1,1)
:::success
ans = 2.0000
:::
integral2与integral3的积分上下限的参数是从里到外
q = integral3(fun,xmin,xmax,ymin,ymax,zmin,zmax)
chapter 10课件
10Integration_&_Differentiation.pdf
方程式求根
解析解(symbolic root)符号化的根
syms x (宣告 x 是 symbolic variable)
syms x
x + x + x
y=(x+x+x)/4
x=sym(‘x’) ; sym 宣告x是symbolic variable
x = sym('x');
x+x+x
y = (x+x+x)/4;
solve 函数求解
equation 默认等式右边 = 0
syms x
y = x*sin(x)-x;
solve(y,x);
syms x
solve(x*sin(x)-x,x);
solve(equation,x); equation 直接写等式,不需要 ‘’ 引号
syms x
%y = cos(x)^2-sin(x)^2;
y = cos(x)^2+sin(x)^2;
solve(y,x)
:::success
Empty sym: 0-by-1 无解
:::
解多个等式
syms x y
eq1 = x - 2*y -5;
eq2 = x + y -6;
root=solve(eq1,eq2,x,y);
:::danger
root.x = 17/3
root.y = 1/3
:::
a,b 代替数值,x与a,b之间关系
syms b x a
root=solve(a*x^2-b);
%%结果:
root =
b^(1/2)/a^(1/2)
-b^(1/2)/a^(1/2)
syms b x a
root=solve(a*x^2-b,b);
%%结果:
root =
a*x^2
:::success
在matlab2020b中,solve(equation)的equation不需要加 ‘’ 引号
:::
exercise
syms a b x y r
root = solve((x-a)^2+(y-b)^2-r^2);
%% 结果
root =
a + (b + r - y)^(1/2)*(r - b + y)^(1/2)
a - (b + r - y)^(1/2)*(r - b + y)^(1/2)
syms a b c d
A = [a,b;c,d];
inv(A)
%%结果
ans =
[ d/(a*d - b*c), -b/(a*d - b*c)]
[-c/(a*d - b*c), a/(a*d - b*c)]
Symbolic Differentiation: diff() 符号的微分
syms x
y = 4*x^5;
yprime=diff(y);
%% 结果:
yprime = 20*x^4
f(x)的微分
f ( x ) = e x 2 x 3 − x + 3 , d f d x = ? f(x)=\frac{e^{x^{2}}}{x^{3}-x+3}, \quad \frac{d f}{d x}=? f(x)=x3−x+3ex2,dxdf=?
syms x
y = exp(x^2)/(x^3-x+3);
yprime = diff(y);
%% 结果:
yprime = (2*x*exp(x^2))/(x^3 - x + 3) - (exp(x^2)*(3*x^2 - 1))/(x^3 - x + 3)^2
对x,y求偏导
g ( x ) = x 2 + x y − 1 y 3 + x + 3 , ∂ f ∂ x = ? , ∂ f ∂ y = ? g(x)=\frac{x^{2}+x y-1}{y^{3}+x+3}, \quad \frac{\partial f}{\partial x}=?,\quad \frac{\partial f}{\partial y}=? g(x)=y3+x+3x2+xy−1,∂x∂f=?,∂y∂f=?
syms x y
equation = (x^2+x*y-1)/(y^3+x+3);
xprime = diff(equation,x); % 对x求偏导
yprime = diff(equation,y); % 对y求偏导
:::success
xprime = (2x + y)/(y^3 + x + 3) - (x^2 + yx - 1)/(y^3 + x + 3)^2
yprime = x/(y^3 + x + 3) - (3y2*(x2 + yx - 1))/(y^3 + x + 3)^2
:::
符号的积分 int()
subs(z,x,0); 替换,把x这个symbolic variable 用 0 替换, 即 Z(0)
syms x;
y = x^2*exp(x);
z = int(y);
%% 结果:
% z=exp(x)*(x^2 - 2*x + 2) 在0处的值不为0,不对
z = z - subs(z,x,0); % 要使初值为0,应该减去上面结果在0处的值
%% 结果:
% z = exp(x)*(x^2 - 2*x + 2) - 2 % Z(0)=0
∫ 0 10 x 2 − x + 1 x + 3 d x \int_{0}^{10} \frac{x^{2}-x+1}{x+3} d x ∫010x+3x2−x+1dx
syms x; y = (x^2-x+1)/(x+3);
z = int(y,0,10); % 积分的上下限为 0,10
z = double(z); % 将z 转化为 double 变量
%% 结果
z = 29.0624
**用symbolic variable 形式的积分,int () , ** y = (x^2-x+1)/(x+3); 等式不用 element 的乘积,即是 * 和 /
z = int(y,0,10); % 积分的上下限为 0,10
y = @ (x) (x.^2-x+1)./(x+3);
root=integral(y,0,10);
也可以用函数指针做,@ ,(数值求积分,所以 y = @ (x) (x.^2-x+1)./(x+3); 是element 乘积 . 和 ./)*
非线性方程组的求解 fsolve
:::warning
initial guess = 0 ----> 从0开始求解f(x)==0 , 即迭代初值是0,解在0附近
等式最右边默认 == 0
:::
f = @(x) (1.2*x+0.3+x*sin(x));
froot=fsolve(f,0);
定义 root2d.m 函数
function f = root2d(x)
f(1) = 2*x(1) - x(2) - exp(-x(1));
f(2) = -x(1) + 2*x(2) - exp(-x(2));
end
:::warning
在命令行窗口: ** fsolve(@root2d,[-5,5] )**
结果:ans = 0.5671 0.5671
即 x1 = 0.5671 x2 = 0.5671
x1 --> x x2 --> y
:::
fsolve详解
fzero() 求解非线性函数的根(求零点)
零点的左右数值符号不同的,因此 y = x^2 用fzero()求解不了
f = @(x) x.^2;
fzero(f,0.1)
:::success
ans = NaN fzero求解失败
:::
f = @(x) x.^2;
fsolve(f,0.1)
:::success
ans = 0.0063
:::
f = @ (x) x.^2;
option = optimset('MaxIter',1e4,'TolFun',1e-10);
x1 = fsolve(f,0.1,option);
:::success
x1 = 1.9532e-04
:::
1e4 --> 迭代的次数,迭代次数越多,越精确
1e-10 --> 误差度
未完待续…