matlab短期课程--基础

课程介绍

学习matlab对于工科生和理科生都是相当重要的,而且matlab的集成效果相当好。算法实现和直观图像结果是matlab的优点。 课程视频:B站MATLAB教程——台大郭彦甫

基本操作与矩阵输入

command line

Calculator

+ - * / ^

先乘除后加减,括号优先。关于更多的三角函数和其他特殊数学数字更重要的是查询help文档。

e \(\pi\) 自然对数
exp(1) pi log
exp()是e指函数 自然对数相当于\(\ln\)

EX: \[ \sin(\sqrt{\pi})+\ln(\tan(1))\]

1
sin(sqrt(pi))+log(tan(1))

计算结果储存在ans当中,可以再对ans进行操作。

Variables
  • 变量不需要提前声明(declare)
  • =是赋值
  • who或者whos可以查看变量的类型
  • Special Variables and Constants
关键字 关键字 关键字 关键字
i,j Inf eps NaN
complex number 无穷大 非常小的数 not a number

iskeyword可以用来查询关键字

  • Calling Priority 由高到低:Variable \(\rightarrow\) Built-in function \(\rightarrow\) Subfunction \(\rightarrow\) Private function (MEX-file P-file M-file)
1
2
3
4
5
6
7
8
9
10
11
cos='This string .'

cos =

'This string .'

>> cos(8)

ans =

'r'

并且clear ans可以清除指定的变量,注意clear会清除所有工作区的变量。

Format
1
2
3
4
5
6
7
8
9
10
11
12
13
>> format long
>> pi

ans =

3.141592653589793

>> format short
>> pi

ans =

3.1416
  • format type有以下几种形式:
short long shortE longE bank hex rat
短型 长型 科学计数法 科学计数法 ex:3.14 转为16进制 转为有理数
  • Calculate:\[\frac{3}{14}+\frac{4}{14}+\frac{5}{15}=\]
1
2
3
4
5
6
7
8
9
10
11
12
13
>> format long
>> (3/13)+(4/14)+(5/15)

ans =

0.849816849816850

>> format rat
>> (3/13)+(4/14)+(5/15)

ans =

232/273
小技巧
  • a=10;a=10的区别在于后者不会显示结果
  • clc clear command window display
  • clear remove all variable in the workspace
  • whowhos show information

Array(Vector and Matrix)

  • vector

a=[1 2 3 4]这是一个行向量(row vector)
b=[1;2;3;4]这是一个列向量(column vector)

  • matrix

A=[1 21 6;5 17 9;31 2 7]这是一个矩阵(matrix)

Array Indexing

\[A=\begin{bmatrix} 1 & 21 & 6 \\ 5 & 17 & 9 \\ 31 & 2 & 7 \\ \end{bmatrix}\]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
>> A(1,2) %第一行,第二列

ans =

21

>> A(2) %第二个,顺序是一列一列地数下去

ans =

5

>> A(8)

ans =

9
1
2
3
4
5
6
7
8
9
10
11
12
13
>> A([1 3],[1 3]) %第一个中括号里的是行数,第二个是列数

ans =

1 6
31 7

>> A([1 3;1 3]) % 按列数的第一个 第三个为第一行;第一个,第三个为第二行。

ans =

1 31
1 31
Replacing Entries

A(1,2)=76这将矩阵中的21转为了76

Colon Operator

Want to create a long array:A=[1 2 3...100]?
A=[1:100]
若等差为2,可以进行以下操作:A=[1:2:100],同时可以和matrix类似使用

delete by colon operator

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
>> a=[1 2 3 ;2 3 5;1 2 3]

a =

1 2 3
2 3 5
1 2 3

>> a(3,:)=[]

a =

1 2 3
2 3 5

Array Concatenation

F=[A B]或者F=[A;B],将矩阵连接。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
>> a=[1 2;3 4];
>> b=[9 9;9 9];
>> F=[a b]

F =

1 2 9 9
3 4 9 9

>> F=[a;b]

F =

1 2
3 4
9 9
9 9
Array的操作
  • Array Manipulation operators on array:+ - * / . '
    .*这是点乘, 1除以1 2除以2(element operation)
    '这是转置,transpose
    +,若是加一个实数,则是将每个entries加上这个实数
1
2
3
4
5
6
7
8
9
10
11
12
13
>> a.*b

ans =

9 18
27 36

>> a*b

ans =

27 27
63 63
相关表格
  • Some Special Matrix
矩阵生成
  • Some Matrix Related Functions

max(A)矩阵中每个column中最大的数字;
max(ma(A))矩阵中的最大数字;
sum(A)矩阵中每个column的sum,mean(A)也是如此;
sort(A)排序每个column的排序;
sortrows(A)排序每个row; size(A) length(A) find(A==m)分别是矩阵的大小(行数和列数)、向量(维度)的长度和寻找等于某数字(m)的位置。

结构化程式与自定义函数

Script Writing

  • script is saved as <file>.m.
  • %一个百分比是comment(注释);%%两个百分比则是section(可以分开程序,分别运行)。
  • 设置断点就进入了debug模式,命令行中是K>> #### script flow
  • A script runs line by line
  • Structured programming techniques are app;ied to make the program looks neat.

flow control

  • if else :condition is true?
  • for
  • switch case
  • try catch
  • while
  • break
  • continue
  • end
  • pause
  • return
logical operators
< <= > >= == ~= && ||
equal to not equal to and or
介绍

if elseif else

1
2
3
4
5
6
7
if condition 1
statement1
elseif condition 2
statement 2
else
statement3
end %elseif and else are optional

EX:

1
2
3
4
5
6
a=3;
if rem(a,2)==0 % remainder 余数
disp('a is even')
else
disp('a is odd')
end

switch

1
2
3
4
5
6
7
8
9
10
11
12
switch expression
case value1
statement1
case value2
statement2

otherwise
statement

end


while

1
2
3
4
5
6
while expression
statement
end

prod(1:n)<1e100 %阶乘小于10的100次方

Exercise: \[\sum_{i=1}^{999}i\]

1
2
3
4
5
6
7
i=1;
sum=0;
while i<=999
sum=sum+i;
i=i+1;
end
disp(sum)

for

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
for variable =start:increment:end
commands
end

%ex
for n=1:2:10
a(n)=2^n;
end
disp(a)%还是会补零进去

%解决
clear a
for n=1:2:9
a((n+1)/2)=2^n;
end
disp(a)%或者给a(n)为a(i),即一个新的变量作为index

  • Pre-allocating Space to Space(预分配)

没有预先分配空间,matlab运行程序会变的比较慢。所以提前给储存数据的数据类型一个确定的大小。
tictoc是用于计时的代码。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
%%
tic
for ii=1:2000
for jj=1:2000
A(ii,jj)=ii+jj;
end
end
toc
%%
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

Exercise: Use structured programming to:
- Copy entries in matrix A to matrix B - Change the values in matrix B if their corresponding entries in matrix A is negative \[ A=\begin{bmatrix} 0 &-1 & 4\\ 9 &-14& 25 \\ -34& 49 &64 \\ \end{bmatrix}\]

1
2
3
4
5
6
7
8
9
10
11
clear
A=[0 -1 4;9 -14 25;-34 49 64];
B=A;
for i=1:3
for j=1:3
if B(i,j)<0
B(i,j)=-B(i,j);
end
end
end
disp(B)

break

  • terminates the execution of for or while loops
  • Used in iteration where convergence is not guaranteed
tips for script writing
  • At the beginning of your script,use commandclear allto remove previous variables andclose allto close all figures
  • Use semicolon;at the end of commands to inhibit unwanted output
  • Use ellipsis...(换行号)to make scripts more readable
  • Press ctrl+c to terminate the script before conclusion

Functions

  • Functions are written when we need to perform routines
    • yes input arguments
    • yes output arguments
    • operate on date in the local workspace
  • edit(which('mean.m'))打开mean函数

User Define Functions

1
2
3
4
function x = freebody(x0,v0,t)
% 解释x0 v0 t
x = x0+v0.*t+9.8*t.*t/2
%点乘是元素与元素相乘,用点乘是为了在遇到多个例子一次计算时避免出错,即input是matrix或者vector

User with Multiple Inputs and Outputs

function[a,F]=acc(v2,v1,t2,t1,m)
当然在做乘除运算时最好要用点乘或点除法

Exercise:

  • Write a function that asks for a temperature in degrees Fahrenheit
  • Compute the equivalent temperature in degrees Celsius
  • Show the converted temperature in degrees Celsius
  • The function should keep running until no number is provided to convert
  • You may want to use these functions:
    • input;isempty;break;disp;num2str

Function Default Variables

  • inputname:variable name of function input
  • mfilename:file name of currently running function
  • nargin:Number of function input arguments
  • nargout:Number of function output arguments
  • varargin`:Variable length input argument list
  • varargout:Variable length output argument list

Function Handles(pointer)

A way to create anonymous functions,i.e.,one line expression functions that do not have to be defined in .mfile.

f=@(x) exp(-2*x);,f指向这个function。

变量与档案存取

Data(Variables) Types

  • Multidlmensional Array
    • logical、char、numeric、cell、struct
  • Scalar
    • function handle(@)

Variable Type Conversion

double()当作function使用,其他同理。int8()八位整型。

char&string

  • char(character)
    • A character is represented in ASCII.
    • whos可以查看内容
    • uint16()可以查看对应的ASCII码
  • string
    • s1='hello';,an array collects characters
    • string concatenation(连接):s3=[s1 s2]s3=[s1;s2]两种

logical operations and assignments

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
>> str='addffdafa'

str =

'addffdafa'

>> str(2) % indexing

ans =

'd'

>> 'a'==str % ==会比较string中所有的字符

ans =

1×9 logical 数组

1 0 0 0 0 0 1 0 1

>> str(str == 'a')='z'

str =

'zddffdzfz' % 替换掉了a字符

%比较整个string请查询help文档

Exercise:
Write a script that inverts any given string
s1='I like the letter E'变为s2='E rettel eht ekil I'

structure

  • A method of storing heterogeneous data
  • It contain arrays called fields
1
2
3
4
5
>> student(2).name='frank';
>> student(2).id=66998845;
>> student(2).grade=[56 55 12;12 13 1;12 15 14]
% 第二个student structure

structure functions
  • cell2struct:convert
  • fieldnames:field names of structure,or public fields of objects
  • getfield:field of structure array
  • isfield isstruct:determine whether input is
  • orderfields:order fields
  • rmfield:remove fields from structure
  • setfield:assign values to structure
  • struct:create struct array
  • structfun:apply function to each field of structure

structure 是可以嵌套的,不断指到下一个。(nesting structure)

1
2
3
4
5
6
7
8
>> A=struct('data',[12 12;11 14],'nest',struct('id',15452,'name','mike'))

A =

包含以下字段的 struct:

data: [2×2 double]
nest: [1×1 struct]

cell array

  • store heterogeneous data
  • similar to matrix but each entry contains different type of date
  • declared using {}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
>> A(1,1)={[1 2 3;4 5 6]};
>> A(1,2)={'mike'};
>> A(2,1)={3+7i};
>> A(2,2)={-pi:pi:pi};
>> A

A =

2×2 cell 数组

{2×3 double } {'mike' }
{[3.0000 + 7.0000i]} {[-3.1416 0 3.1416]}
%或者把花括号放到圆括号的位置

matlab中是将A(1,1)作为pointer,这样就可以使得每个entries不同。

accessing cell array
  • {}are used to access the "content" of cell arrays
  • differences:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
>> A(1,1)

ans =

1×1 cell 数组

{2×3 double}

>> A{1,1}

ans =

1 2 3
4 5 6
cell array functions
  • cell create cell array
  • cell2mat convert array to numeric array
  • cell2struct convert
  • celldisp cell array contents
  • cellfun apply function to each cell in cell array
  • cellplot graphically display structure of cell array
  • cellstr create cell array of strings from character array
  • iscell determine whether input is cell array
  • mat2cell convert
  • num2cell convert
  • struct2cell convert

ex:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
>> a=magic(3)

a =

8 1 6
3 5 7
4 9 2

>> b=num2cell(a)

b =

3×3 cell 数组

{[8]} {[1]} {[6]}
{[3]} {[5]} {[7]}
{[4]} {[9]} {[2]}


>> c=mat2cell(a,[1,1,1],3)

c =

3×1 cell 数组

{[8 1 6]}
{[3 5 7]}
{[4 9 2]}
% 中括号是row,最后的数字是column

multidimensional array(row column layer)
  • 直接创建
  • cat() array concatenation 连接array
  • reshape returns a new array with assigned rows and columns
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
>> A=[1 2;1 4];
>> B=[1 6;1 5];
>> C=cat(1,A,B)

C =

1 2
1 4
1 6
1 5

>> D=cat(2,A,B)

D =

1 2 1 6
1 4 1 5

>> F=cat(3,A,B)

F(:,:,1) =

1 2
1 4


F(:,:,2) =

1 6
1 5
%这样就有两个layer



>> a=reshape(A,1,4)

a =

1 1 2 4

checking variables and variable status

isfunction 例如,isinteger查看是否为整数。

File Access

File Content Extension Description Import Function Export Function
Matlab formatted data MAT Saved Matlab workspace load save
Text Space delimited numbers load save
spreadsheet XLS,XLSX excel xlsread xlswrite
  • save() and load()

save mydata.mat -ascii 储存形式为ASCII码,也可以不用添加;
load 'mydata.mat','-ascii'

excel file reading and writing :xlsread() xlswrite()

score = xlsread('04Score.xlsx','B2:D4')读取对应sheet里面的数据(string中的东西可能不在)
xlswrite('04Score.xlsx',M,1,'E2:E4');写入到对应的位置,M为写入的变量,1是sheet
xlswrite('04Score.xlsx',{'Mean'},1,'E1');加入Mean标条

getting text in excel spreadsheet

[score header]=xlsread('04score.xlsx');读取了text部分,当然也可以同时写入到Excel里面

low-level file input/output

  • Read and write file at the byte or character level
  • A file has ID fid(本质上是pointer)
  • Location in the file is specified by a pointer that can be moved around
low-level I/O functions
  • fopen open file or obtain information about open file

  • fclose close

  • fscanf read data from text file

  • fprintf write data to text file

  • feof test for en-of-file

  • open and close file

    • fid =fopen('[filename]','[permission]');permission(采取的操作)读取r或者写入w
    • status=fclose(fid)
  • 顺序是:先generate出数据,再打开file,然后将数据write into the file,最后close the file

1
2
3
4
5
6
7
8
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
read and write through formatted I/O
  • Read A=fscanf(fid,format,size);
  • Write fprintf(fid,format,x,y,...);
  • format 是format specifier %d %f %n
  • size 是amount of data to read
  • x,y,...是 data to write

ex:

Example

初阶绘图

basic plotting

plot from "Data"

  • Matlab does not understand functions \[f(t)=\sin(2\pi t)\]
  • Strategies:
    • generate the numeric values of function over specific range
    • display the data "points" in a graphical way

plot()

  • plot(x,y) plots each vector pairs(x,y)
  • plot(y)plots each vector pairs(x,y),where x=[1...n],n=length(y)

hold on/off

  • use hold on to have both plots in one figure
  • hold on打头,hold off结尾,在script里面使用

plot style

  • plot(x,y,'str')plots each vector pairs(x,y) using the format defined in str(更多操作进入help中的 linespec查看)
细节

legend()

  • add legend to graph `legend('L1',...)
  • position adjustment
1
2
3
4
5
6
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');
结果

title()and?label()

  • title()
  • xlabel()
  • ylabel()
  • xlabel()
1
2
3
4
5
6
7
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}');
结果

text()andannotation()

  • text with mathematical expression using Latex
1
2
3
4
5
6
x=linspace(0,3);y=x.^2.*sin(x);
plot(x,y);
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]);%x的位置,y的位置
结果

Exercise:

  • plot \(f\) as a black line and \(g\) as a series of red circles for the range \(t=1\) to \(2\) in one figure \[f=t^2 \quad g=\sin(2\pi t)\]
  • label each axis, and add title and legend

graphical object properties

figure adjustment

  • several properties:
    • font
    • font size
    • ine width
    • axis limit
    • tick position
    • tick label
  • 调整figure的一些性质

graphical objects

  • a figure is composed of many objects
    1
    2
    3
    4
    5
    x=linspace(0,2*pi,1000);
    y=sin(x);
    plot(x,y);
    set(gcf,'Color',[1,1,1]);

结果

figure properties

得到figure后,可以进入编辑中的图窗属性。可以对像axes、line等一些objects进行细致地修改。(figure line axes)

modifying properties of an object

  • Strategy:
    • Identify the "handle" of an object
    • fetch(拉取) or modify(修改) the object's properties
  • For example, to change the limits of the x-axis:
    • Find the handle of the x-axis
    • Modify the limits
identifying the handle of an object
  • upon creation h=plot(x,y)储存辨识码
  • utility functions(找出辨识码):
    • gcareturn the handle of the "current" axes
    • gcfreturn the handle of the "current" figure
    • allchidfind all children of specified objects
    • ancestorfind ancestor of graphics object
    • deletedelete an object
    • findall find all graphics objects
fetching or modifying properties
  • to fetch properties,use get()
  • to modify properties,useset()
getting object properties

get()可以得到非常多的图形性质,找到相关的图形确切的性质

modifying properties
  • setting axes limits
    • set(gca,'XLim',[0,2*pi]);
    • set(gca,'YLim',[-1.2,1.2]);
    • Alternatives:xlim([0,2*pi]);
  • setting font and tick of axes
    • set(gca,'FontSize',25);改变axes的字体大小为25
    • set(gca,'XTickLabel',0:90:360);改变x轴的单位区间和lim
    • set(gca,'FontName','symbol')将x轴的字体名称设为符号,这样xticklabel可以改为\(\pi\)相关的属性

line specification

  • line style and width:set('LineStyle','-.','LineWidth',7.0,'Color','g');
  • alternative:plot(x,y,'-.g',...,'LineWidth',7.0)

marker specification

  • face and edge colors of the marker
    1
    2
    3
    4
    5
    x=rand(20,1);
    set(gca,'FontSize',18);
    plot(x,'-md','LineWidth',2,'MarkerEdgeColor','k',...
    'MarkerFaceColor','g','MarkerSize',10);
    xlim([1,20]);
结果

multiple figures

  • create a figure window by calling figure figure,plot(x,y1):

  • be careful when using the gcf handle where there exists multiple figures

  • figure position and size figure('Position',[left,bottom,width,height]);

  • several small plots in a figure (subplot) subplot(m,n,1);m是行,n是列,1是该幅图的位置

    1
    2
    3
    4
    5
    6
    7
    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 %x和y的大小相同
    subplot(2,2,4);plot(x,y);axis equal tight

结果

control of grid and box and axis

课程内容

saving figures into files

saveas(gcf,'<filename>','formattype');,高解析度还是使用print为妙 课程内容

进阶绘图

advanced 2D plots

special plots

  • function
    • loglog graph with logarithmic(对数的) scales for both axes
    • semilogx graph with a logarithmic scale for the x-axis and a linear scale for the y-axis
    • semilogy graph with a logarithmic scale for the y-axis and a linear scale for the x-axis
    • plotyy graph with y-tick labels on the left and right side
  • function
    • hist histogram plot(直方图)
    • bar bar graph
    • pie pie chart
    • polar polar coordinate plot

logarithm plots

x=logspace(-1,1,100)产生一个对数变量,从\(10^{-1}\)\(10\)
set(gca,'XGid','on') 对下面的程序可以设置网格

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
x=logspace(-1,1,100);
y=x.*2;
subplot(2,2,1);
plot(x,y);
title('Plot');
subplot(2,2,2);
semilogx(x,y);
title('Semilogx');
subplot(2,2,3);
semilogy(x,y);
title('Semilogy');
subplot(2,2,4);
loglog(x,y);
title('Loglog');

结果

plotyy()意思是有两个y轴

1
2
3
4
5
6
7
8
x=0:0.01:20;
y1=200*exp(-0.05*x).*sin(x);
y2=0.8*exp(-0.5*x).*sin(10*x);
[AX,H1,H2] = plotyy(x,y1,x,y2);
set(get(AX(1),'Ylabel'),'String','Left Y-axis')
set(get(AX(2),'Ylabel'),'String','Right Y-axis')
title('Labeling plotyy');
set(H1,'LineStyle','--');set(H2,'LineStyle',':');
结果

histogram

1
2
3
4
5
6
7
y=randn(1,1000);
subplot(2,1,1);
hist(y,10);
title('Bins=10');
subplot(2,1,2);
hist(y,50);%后面是设置多少个直方条
title('Bins=50');
结果

bar charts

1
2
3
4
5
6
x=[1 2 5 4 8];
y=[x;1:5];%实际上,y是一个两行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');

结果

还有其他种类的bar chart(stacked栈 and hortizontal bar charts)

1
2
3
4
5
6
7
8
9
10
x=[1 2 5 4 8];
y=[x;1:5];
subplot(1,2,1);
bar(y,'stacked');
title('Stacked');

subplot(1,2,2);
barh(y);
title('Horizontal');

结果

pie charts

修改以下pie()中的方括号的数据可以控制每个部分是否分开

1
2
3
4
5
6
clear
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,[0,0,0,1]);

结果

polar char

1
2
3
4
5
6
7
8
9
10
11
12
13
14
x=1:100;
theta=x/10;
r=log10(x);
subplot(1,4,1);polar(theta,r);

theta=linspace(0,2*pi);r=cos(4*theta);
subplot(1,4,2);polar(theta,r);

theta=linspace(0,2*pi,6);r=ones(1,length((theta)));%6实际上是包括了0和2*pi端点值
subplot(1,4,3);polar(theta,r);

theta=linspace(0,2*pi);r=1-sin(theta);
subplot(1,4,4);polar(theta,r);

结果

stairs and stem charts

1
2
3
4
5
x=linspace(0,4*pi,40);
y=sin(x);
subplot(1,2,1);stairs(y);
subplot(1,2,2);stem(y);

结果

Exerise:
- plot a function:\(f(t)=\sin(\frac{\pi t^2}{4})\) - add the points sampled at 5 Hz using stem()

boxplot and error bar

常用于统计应用中

1
2
3
4
5
6
7
8
load carsmall
subplot(2,1,1);
boxplot(MPG,Origin);
subplot(2,1,2);
x=0:pi/10:pi;y=sin(x);
e=std(y)*ones(size(x));
errorbar(x,y,e);

结果

stop sign

fil() 将坐标拆成8个等分,绘制八边形。fill的原理是旋转绘制。

1
2
3
4
5
t=(1:2:15)'*pi/8;x=sin(t);y=cos(t);
fill(x,y,'r');axis square off;
text(0,0,'STOP','Color','w','FontSize',80,...
'FontWeight','bold','HorizontalAlignment','center');

结果

color space

  • [R G B]三色红绿蓝来调制颜色
    • 0 is minimun
    • 1 is maximum
    • 8-bit equivalence
1
2
3
4
5
6
7
8
9
10
11
12
13
14
clear;
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('Medal count for top 5 countries in 2012 Olypics');
ylabel('Number of medals');xlabel('Country');
legend('Gold','Silver','Bronze');
set(gca,'XTickLabel',{'USA','CHN','GBR','RUS','KOR'});
set(h(1),'facecolor',[1 0.8 0.2]);
set(h(2),'facecolor',[0.8 0.8 0.8]);
set(h(3),'facecolor',[0.8 0.4 0]);

结果

visualizing data as an image:imagesc()

  • display values of matrix as an "image"
1
2
3
4
5
6
7
8
9
[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');

结果 - color bar and scheme

colorbar colormap(cool) colormap(hot) colormap(gray)
加入色条 冷色map 暖色map 灰色map
  • build-in colormaps
    • use built-in color mapscolormap([name])
    • a color map is a matrix of 256 times 3 a=colormap(prism)
    • use a customized color map a=ones(256,3; colormap(a);

3D plots

Function Description
plot3 3-D line plot
surf 3-D shaded surface plot
surfc contour(轮廓) plot under a 3-D shaded surface plot
surface create surface object
meshc plot a contour graph under mesh graph
contour contour plot of matrix
contourf filled 2-D contour plot

2D vs 3D 2D的图像也可以显示在3D上面。

plot3()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
%%
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');grid on;
xlabel('x-axis'); ylabel('y-axis');zlabel('z-label');
%%
clear;
t=0:pi/50:10*pi;
plot3(sin(t),cos(t),t);
grid on; axis square;
%%
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;

结果1 结果2 结果3 这里是线穿起来的三维图,vector确定点,点连为线

principles of 3D surface plots

  • usually for plotting functions:\(z=f(x,y)\)
  • need to provide matlab a set of (x,y,z) points
  • use meshgrid to create matrices X and Y for a given range
1
2
3
4
x=-2:1:2;
y=-2:1:2;
[X,Y]=meshgrid(x,y);X和Y是矩阵,得到矩阵尤为重要

mesh()andsurf()

1
2
3
4
5
6
7
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);% axis aquare会更漂亮,效果见下一个例子
subplot(1,2,2); surf(X,Y,Z);

结果

contour()
- projection of equal heights of 3D plot onto a 2D plane

1
2
3
4
5
6
7
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);axis square;
subplot(1,2,2); contour(X,Y,Z);axis square;

结果
1
2
3
4
5
6
7
8
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;

结果

meshc()andsurfc()
- combination of surface/mesh and contours

1
2
3
4
5
6
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);axis square;
subplot(1,2,2); surfc(X,Y,Z); axis square;
结果

view angle:view()
- vary the view angle view(-45,20)

1
2
3
4
5
6
7
8
sphere(50);
shading flat;
light('Position',[1 3 2]);
light('Position',[-3 -1 3]);
material shiny;
axis vis3d off;
set(gcf,'Color',[1 1 1]);
view(-45,20);观察的角度
结果

light:light()用于打光

1
2
3
4
5
6
7
8
9
10
clear;
[X,Y,Z]=sphere(64);
h=surf(X,Y,Z);
axis square Vis3d off;
reds=zeros(256,3); red(:, 1)=(0:256.-1)/255;
colormap(reds); shading interp; lighting phong;
set(h,'AmbientStrength',0.75,'DiffuseStrength',0.5);
L1=light('Position',[-1 -1 -1]);
set(L1,'Position',[-1 -1 1],'Color','g');

结果

patch()
- a graphical object containing polygons

1
2
3
4
5
6
7
8
9
10
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;

结果

professional

1
2
3
4
5
6
7
8
clear;
load cape
x=conv2(ones(9,9)/81,cumsum(cumsum(rand(100,100)),2));
surf(X,'EdgeColor','none','EdgeLighting','Phong',...
'FaceColor','interp');
solormap(map);caxis([-10,300]);%我的显示好像不太正确
grid off; axis off;

pro