MATLAB速成笔记
赋值
a = 1
a = [1 2 3]
a = [1 2 3; 4 5 6; 7 8 9]
使用ones, zeros, rand等函数构造
z = zeros(5, 1)
b = rand(3, 5, 2) %三行五列两张表
矩阵运算
a = [1 2 3; 4 5 6; 7 8 9]
a + 10
sin(a)
a’
inv(a)
format long/short
a * a
a .*a
a .^ a
串联
A = [a, a]
A = [a; a]
复数
sqrt(-1)
c = [3 + 4i, 4 + 3i; -i, 10j]
数组索引
a = [1 2 3; 4 5 6; 7 8 9]
A(3, 2)
A(8)%以列为顺序
start:end
A(1:3, 2)
A(:, 2)
start:step:end
b = 1:10:100
工作区变量
A = magic(4)
save myfile.mat
clear
load myfile.mat
文本和字符
t = “hello world”
t = "hello ""hello world"" world"
t = t + t
a = ["a", "aa"; "b", "bb"]
strlength(a)
seq = “hello world”
seq(4)
seq2 = [seq]
函数
a = [1 3 5]
max(a)
b = [2 4 6]
max(a, b)
disp(‘hello world’)
clc
二维图
x = 0:pi/100:2*pi;
y = sin(x);
plot(x,y)
x = 0:pi/100:2*pi;
y = sin(x);
plot(x,y)
hold on
y2 = cos(x);
plot(x,y2,':')
legend('sin','cos')
hold off
三维图
[X,Y] = meshgrid(-2:.2:2);
Z = X .* exp(-X.^2 - Y.^2);
surf(X,Y,Z)
meshgrid创造了xoy面
z通过.*的方式算出对应的点上z的值
\[Z = X · e^{-X^2-Y^2} \]子图
t = 0:pi/10:2*pi;
[X,Y,Z] = cylinder(4*cos(t));
subplot(2,2,1); mesh(X); title('X');
subplot(2,2,2); mesh(Y); title('Y');
subplot(2,2,3); mesh(Z); title('Z');
subplot(2,2,4); mesh(X,Y,Z); title('X,Y,Z');
脚本
edit mysphere
% Create and plot a sphere with radius r.
[x,y,z] = sphere; % Create a unit sphere.
r = 2;
surf(x*r,y*r,z*r) % Adjust each dimension and plot.
axis equal % Use the same scale for each axis.
% Find the surface area and volume.
A = 4*pi*r^2;
V = (4/3)*pi*r^3;
mysphere
脚本流程控制
N = 100;
f(1) = 1;
f(2) = 1;
for n = 3:N
f(n) = f(n-1) + f(n-2);
end
f(1:10)
a = 0; fa = -Inf;
b = 3; fb = Inf;
while b-a > eps*b
x = (a+b)/2;
fx = x^3-2*x-5;
if sign(fx) == sign(fa)
a = x; fa = fx;
else
b = x; fb = fx;
end
end
x
fid = fopen('magic.m','r');
count = 0;
while ~feof(fid)
line = fgetl(fid);
if isempty(line) || strncmp(line,'%',1) || ~ischar(line)
continue
end
count = count + 1;
end
fprintf('%d lines\n',count);
fclose(fid);
a = 0; fa = -Inf;
b = 3; fb = Inf;
while b-a > eps*b
x = (a+b)/2;
fx = x^3-2*x-5;
if fx == 0
break
elseif sign(fx) == sign(fa)
a = x; fa = fx;
else
b = x; fb = fx;
end
end
x
num = randi(100)
if num < 34
sz = 'low'
elseif num < 67
sz = 'medium'
else
sz = 'high'
end
[dayNum, dayString] = weekday(date, 'long', 'en_US');
switch dayString
case 'Monday'
disp('Start of the work week')
case 'Tuesday'
disp('Day 2')
case 'Wednesday'
disp('Day 3')
case 'Thursday'
disp('Day 4')
case 'Friday'
disp('Last day of the work week')
otherwise
disp('Weekend!')
end
isequal(A, B)判断矩阵相等
文档
doc mean
mean(
help mean
矩阵
A = [16 3 2 13; 5 10 11 8; 9 6 7 12; 4 15 14 1]
sum(A) % 列和
sum(A')' % 行和
sum(A, 2) % 行和
diag(A) % 主对角线元素
sum(diag(A)) % 主对角线元素和
sum(diag(pliplr(A))) %副对角线元素和
magic(4) % 创建任意大小的幻方矩阵
zeros
ones
rand
randn % 正态分布的随机元素
表达式
n = 28
sort([3 + 4i, 4 + 3i])
n = (0:9)’;
pows = [n n .^ 2 2 .^ n]
内置数学函数
io
format short/long/bank/rat/hex
;不显示输出
...长语句
索引
find函数用语指定逻辑条件相符的数组元素的索引。
k = find(isprime(A))‘
A(k)
数组
p = perms(1:4) % 生成排列
A = magic(4)
M = zeros(4, 4, 24);
for k = 1:24
M(:, :, k) = A(:, p(k, :))
size(M)
A = magic(4)
C = {A sum(a) prod(prod(a))}
强制类型转换
s = 'hello'
a = double(s)
s = char(a)
结构体
S = name: 'clo91eaf'
score: 83
grade: 'B+'
S.name
S(2).name = 'clo92eaf'
S(3) = struct('name','clo93eaf',...
'score', 70, 'grade', 'C')
scores = [S.score]
function avg = avgscore(testscores, student, first, last)
for k = first:last
scores(k) = testscores.(student).week(k);
end
avg = sum(scores)/(last - first + 1);
线性代数
C = randi(10, 3, 2)
u = [3; 1; 4]
v = [2 0 1]
s = 7
z = [1+2i 7-3i 3+4i; 6-2i 9i 4+7i]
z' %共轭转置
z.' %非共轭转置
eye(m, n) %单位矩阵
inv(A) %矩阵求逆
det(A) %行列式结果
Ax = b
x = A\b %使用矩阵反斜杠运算符计算x值
xA = b
x = b/A
kron(X, I) %张量积
norm(x, p) %向量x的p范数
norm(A, p)
线性方程组
分解
幂和指数
特征值
奇异值
非线性函数的运算
句柄
fhandle = @sin
fhandle(arg1, arg2, ...);
复合函数
type hump
数据分析
数据预处理
load count.dat
% 缺省项NaN
c3 = count(:,3); % Data at intersection 3
c3NaNCount = sum(isnan(c3))
% 离群值
h = histogram(c3,10); % Histogram
N = max(h.Values); % Maximum bin count
mu3 = mean(c3); % Data mean
sigma3 = std(c3); % Data standard deviation
hold on
plot([mu3 mu3],[0 N],'r','LineWidth',2) % Mean
X = repmat(mu3+(1:2)*sigma3,2,1);
Y = repmat([0;N],1,2);
plot(X,Y,'Color',[255 153 51]./255,'LineWidth',2) % Standard deviations
legend('Data','Mean','Stds')
hold off
% 将离群值替换为NaN值
outliers = (c3 - mu3) > 2*sigma3;
c3m = c3; % Copy c3 to c3m
c3m(outliers) = NaN; % Add NaN values
plot(c3m,'o-')
hold on
% 简单移动平均平滑处理NaN值或filter平滑曲线
span = 3; % Size of the averaging window
window = ones(span,1)/span;
smoothed_c3m = convn(c3m,window,'same');
h = plot(smoothed_c3m,'ro-');
legend('Data','Smoothed Data')
% filter
smoothed2_c3m = filter(window,1,c3m);
delete(h)
plot(smoothed2_c3m,'ro-','DisplayName','Smoothed Data');
% 汇总数据
% 使用mean、median和mode计算常见位置度量或“集中趋势”:
load count.dat
x1 = mean(count)
x2 = median(count)
x3 = mode(count)
% 规模度量
dx1 = max(count)-min(count)
dx2 = std(count)
dx3 = var(count)
%分布形状
figure
hist(count)
legend('Intersection 1',...
'Intersection 2',...
'Intersection 3')
%参数模型提供分布形状的汇总分析。指数分布和数据均值指定的参数 mu 非常适用于流量数据:
c1 = count(:,1); % Data at intersection 1
[bin_counts,bin_locations] = hist(c1);
bin_width = bin_locations(2) - bin_locations(1);
hist_area = (bin_width)*(sum(bin_counts));
figure
hist(c1)
hold on
mu1 = mean(c1);
exp_pdf = @(t)(1/mu1)*exp(-t/mu1); % Integrates
% to 1
t = 0:150;
y = exp_pdf(t);
plot(t,(hist_area)*y,'r','LineWidth',2)
legend('Distribution','Exponential Fit')
% 可视化数据
% 二维散点图
% 三维散点图
% 散点图数组
% 数据建模
load count.dat
c3 = count(:,3); % Data at intersection 3
tdata = (1:24)';
p_coeffs = polyfit(tdata,c3,6);
figure
plot(c3,'o-')
hold on
tfit = (1:0.01:24)';
yfit = polyval(p_coeffs,tfit);
plot(tfit,yfit,'r-','LineWidth',2)
legend('Data','Polynomial Fit','Location','NW')
基本绘图函数
x = 0:pi/100:2*pi;
y = sin(x);
plot(x,y)
xlabel('x = 0:2\pi')
ylabel('Sine of x')
title('Plot of the Sine Function','FontSize',12)
% 多个图表
x = 0:pi/100:2*pi;
y = sin(x);
y2 = sin(x-.25);
y3 = sin(x-.5);
plot(x,y,x,y2,x,y3)
% 指定线型和颜色
plot(x,y,'color_style_marker')
% 绘制线条和标记
plot(x,y,'ks')
x1 = 0:pi/100:2*pi;
x2 = 0:pi/10:2*pi;
plot(x1,sin(x1),'r:',x2,sin(x2),'r+')
% 绘制虚数和复数数据
plot(Z)
% 其中 Z 是复数向量或矩阵,等效于
plot(real(Z),imag(Z))
% 下列语句将绘制一个具有 20 条边的多边形,并在各顶点处绘制一个小圆圈。
t = 0:pi/10:2*pi;
plot(exp(1i*t),'-o')
axis equal
% subplot绘制子图
% 控制轴
创建网格图/曲面图
-
mesh
生成仅使用颜色来标记连接定义点的线条的线框曲面图。 -
surf
使用颜色显示曲面图的连接线和面。 -
meshgrid
函数将一个向量或两个向量(即x
和y
)指定的域转换为矩阵X
和Y
,以便用于计算包含两个变量的函数。X
的行是向量x
的副本,Y
的列是向量y
的副本。
[X,Y] = meshgrid(-8:.5:8);
R = sqrt(X.^2 + Y.^2) + eps;
Z = sin(R)./R;
mesh(X,Y,Z)
绘制正弦函数
脚本和函数
type rank
function r = rank(A,tol)
%RANK Matrix rank.
% RANK(A) provides an estimate of the number of linearly
% independent rows or columns of a matrix A.
%
% RANK(A,TOL) is the number of singular values of A
% that are larger than TOL. By default, TOL = max(size(A)) * eps(norm(A)).
%
% Class support for input A:
% float: double, single
% Copyright 1984-2015 The MathWorks, Inc.
s = svd(A);
if nargin==1
tol = max(size(A)) * eps(max(s));
end
r = sum(s > tol);
help rank
匿名函数
sqr = @(x) x.^2
a = sqr(5)
全局变量
function h = falling(t)
gloval GRAVITY
h = 1/2*GRAVITY*t.^2
>> global GRAVITY
>> GRAVITY = 32;
>> y = falling((0:.1:5)');
命令与函数语法
foo == foo('a', 'b', 'c')