matlab-note-origin

matlab-note-origin

Charles Lv7

matlab-note-origin

这是之前网课的部分matlab笔记,在此一并存放(只有源码,具体知识点看注释)

Part1

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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
%矩阵
A = [1 2 3; 2 3 1; 3 2 4]
%转置
B = A'
%竖列
C = A(:)
%矩阵求逆
D = inv(A)
%生成全0矩阵(3个10*5的矩阵)
E = zeros(10, 5, 3)
E(:, :, 1) = rand(10, 5)
E(:, :, 2) = randi(5, 10, 5)
E(:, :, 3) = randn(10, 5)
%%
% 元胞数组
A = cell(1, 6)
A{2} = eye(3)
A{5} = magic(5) %幻方
B = A{5}
%%
%结构体
books = struct('name', {{'Machine Learning', 'Data Mining'}}, 'price', [30 40])
books.name
books.name(1)
books.name{1}
%%
%MATLAB 矩阵操作
A = [1 2 3 4 5 8 5 4 6]
B = 1:2:9
C = repmat(B, 3, 1)
D = ones(2, 4)
%%
%
A = [1 2 3 4; 5 6 7 8]
B = [1 1 2 2; 2 2 1 1]
C = A + B
D = A - B
E = A * B'
F = A .* B %对应项相乘
G = A / B;
H = A ./ B
%%
A = magic(5)
B = A(2, 3)
C = A(3, :)
D = A(:, 4)
[m, n] = find (A > 20)
%%
sum = 0;

for n = 1:5
sum = sum + n ^ 2;
end

%%
s = 0;
n = 1;

while n <= 10
s = s + n;
n = n + 1;
end

%%
a = 100;
b = 20;

if a > b
'成立'
else
'不成立'
end

%%
%二维绘图
x = 0:0.01:2 * pi;
y = sin(x);
figure %建立一个幕布
plot(x, y)
title('y=sin(x)')
xlabel('x')
ylabel('sin(x)')
xlim([0 2 * pi])

x = 0:0.01:20;
y1 = 200 * exp(-0.05 * x) .* sin(x);
y2 = 0.8 * exp(-0.5 * x) .* sin(10 * x);
figure
[AX, H1, H2] = plotyy(x, y1, x, y2, 'plot');
set(get(AX(1), 'Ylabel'), 'String', 'Slow Decay')
set(get(AX(2), 'Ylabel'), 'String', 'Fast Decay')
xlabel('Time (\musec)')
title('Multple Decay Rates')
set(H1, 'LineStyle', '--')
set(H2, 'LineStyle', ':')

%%
%三维立体绘图
t = 0:pi / 50:10 * pi;
plot3(sin(t), cos(t), t)
xlabel('sin(t)')
ylabel('cos(t)')
zlabel('t')
grid on
axis square
%%
%图形保存和导出
%(1).Edit->Copy Figure
%(2).Toolbar->Save
%(3).print('-depsc','-tiff','-r300','picturel')
%(4).File->Export Setup

%%
% MATLAB文件导入
[x, y, z] = peaks(30);
mesh(x, y, z)
grid

%%
%完结

Part2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
%% 求解方程
%方法一:
p = [1, -3, 1]
x = roots(p)

%方法二: 绘制函数图像
x = -5:0.1:5;
y1 = x .* x - 3 * x + 1;
y2 = zeros(size(x));
plot(x, y1, x, y2);

%方法三: 调用fzero函数
f = @(x)x * x - 3 * x + 1;
x1 = fzero(f, 0.5)
x2 = fzero(f, 2.5) %即2.5附近的方程根

%方法四: 调用fsolve函数
f = @(x)x * x - 3 * x + 1;
x1 = fsolve(f, 0.5, optimset('Display', 'off'))
x2 = fsolve(f, 2.5, optimset('Display', 'off'))
  • Title: matlab-note-origin
  • Author: Charles
  • Created at : 2023-02-03 12:45:48
  • Updated at : 2023-08-17 09:48:37
  • Link: https://charles2530.github.io/2023/02/03/matlab-note-origin/
  • License: This work is licensed under CC BY-NC-SA 4.0.
Comments
On this page
matlab-note-origin